Problem 121
Add Two Numbers as Lists
Medium · 20 pts · Linked List, Math
Problem
Two non-negative integers are stored as linked lists of digits in reverse order: the head holds the ones digit, the next node the tens digit, and so on. Add the two numbers and print the sum in the same format, ones digit first. The numbers can have up to 100 digits, far too many for any built-in integer type, so add them digit by digit like on paper. Walk through both lists together, add the two digits and the carry, output the sum mod 10, and carry the sum / 10 to the next position. Remember a final carry.
Input
Four lines: N, the N digits of the first number (ones digit first), M, the M digits of the second number.
Output
Print the digits of the sum, ones digit first, space-separated.
Constraints
1 <= N, M <= 100; digits are 0-9; numbers have no leading zeros except the number 0 itself
Example input
3 2 4 3 3 5 6 4
Example output
7 0 8
Explanation
The lists 2 4 3 and 5 6 4 stand for 342 and 465. Their sum is 807, which is written in reverse as 7 0 8.