Stadium Gate Tallies

MediummathAlso known as Add Two Numbers

A stadium counts fans at its north and south gates with old counters that store a number as a chain of digits, ones digit first. So 4,071 fans is stored as 1 → 7 → 0 → 4. The counters were built to grow without limit, so a tally can be far longer than any built-in integer type can hold.

At the end of the night the stadium needs the total for both gates, stored the same way.

Your task

Write addTallies(north, south). Each argument is a non-empty linked list of digits (0 to 9), ones digit first. Return a linked list holding the sum, in the same format.

The lists may have different lengths. Neither has extra zeros at the end of the chain (its highest digit), except the number 0 itself, which is [0]. The result must follow the same rule.

addTallies(north: ListNode, south: ListNode) → ListNode

Examples

Example 1
Input
north = [1, 7, 0, 4]
south = [9, 5, 6]
Output
[0, 3, 7, 4]
Why

That is 4,071 + 659 = 4,730. Ones: 1 + 9 = 10, write 0 carry 1. Tens: 7 + 5 + 1 = 13, write 3 carry 1. Hundreds: 0 + 6 + 1 = 7. Thousands: 4. Read ones first: 0, 3, 7, 4.

Example 2
Input
north = [8, 9]
south = [4]
Output
[2, 0, 1]
Why

98 + 4 = 102. 8 + 4 = 12, write 2 carry 1. 9 + 1 = 10, write 0 carry 1. Both lists are finished but a carry is left, so it becomes a new digit, 1.

Constraints

  • 1 ≤ length of each list ≤ 100
  • 0 ≤ each digit ≤ 9
  • Numbers can have up to 100 digits, so do not convert them to built-in numbers.
Start with brute force

Turn each chain into a number, add the two numbers, and turn the result back into a chain.

That breaks as soon as a tally passes about 16 digits: JavaScript numbers lose precision beyond 9,007,199,254,740,991, and many languages overflow at 64 bits. With up to 100 digits the answer would be wrong. Python's integers grow without limit, so there it happens to work, but it skips the skill this problem is about. Adding digit by digit works for any length, in any language.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code