codejump
MediumPythonJavaScriptTypeScript

Linked List — Add Two Numbers

Data StructuresLinked ListMath

solve(a, b) — two non-negative integers are stored as linked lists of digits in
reverse order: [2,4,3] is the number 342. Add them and return the sum in the same
format (an array of digits, least significant first). Neither input has leading zeros
except the number 0 itself.

The numbers can be far longer than any integer type, so do the addition digit by digit
with a carry, like on paper. Keep going while either list has digits or a carry
is left — [9,9,9,9] + [1] ends with an extra digit.

Examples

solve([2,4,3], [5,6,4])   → [7,0,8]      // 342 + 465 = 807
solve([0], [0])           → [0]
solve([9,9,9,9], [1])     → [0,0,0,0,1]

Sample tests

Test #1Classic example
Input: [[2,4,3],[5,6,4]]
Output: [7,0,8]
Test #2Zero plus zero
Input: [[0],[0]]
Output: [0]
Test #3Carry grows the result
Input: [[9,9,9,9],[1]]
Output: [0,0,0,0,1]