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: 4,071 fans is 1 → 7 → 0 → 4. A tally can be too long for any built-in integer type to hold.

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

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

The lists are 4,071 and 659, and their sum is 4,730. In the ones place, 1 + 9 = 10, so you write 0 and carry 1. In the tens place, 7 + 5 + 1 = 13, so you write 3 and carry 1. In the hundreds place, 0 + 6 + 1 = 7, and the thousands place is just 4. Written ones digit first, the result is 0, 3, 7, 4.

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

The lists are 98 and 4, and their sum is 102. In the ones place, 8 + 4 = 12, so you write 2 and carry 1. In the tens place, 9 + 1 = 10, so you write 0 and carry 1. Both lists are finished but a carry is left, so it becomes a new final 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, and turn the result back into a chain.

That breaks past about 16 digits: JavaScript numbers lose precision beyond 9,007,199,254,740,991, and many languages overflow at 64 bits. Python's integers grow without limit, so this approach works there, but it avoids the digit-by-digit addition that this problem is meant to practice.

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