MediumLinked ListMathRecursion

1 approach, code in every language

Problem description

You are given two non-empty linked lists that each represent a non-negative integer. The digits are stored in reverse order, so the head of the list holds the least significant digit, and every node contains exactly one digit.

Add the two numbers together and return the result as a linked list, using the same reverse-order digit layout. You may assume that neither number has any leading zeros, except for the number zero itself.

Example 1

Input: l1 = [2,4,3], l2 = [5,6,4]

Output: [7,0,8]

The lists encode 342 and 465. Their sum is 807, which written back in reverse-digit order is 7 -> 0 -> 8.

Example 2

Input: l1 = [9,9,9], l2 = [1]

Output: [0,0,0,1]

This is 999 + 1 = 1000. The carry ripples through every digit and produces a new most significant node, giving 0 -> 0 -> 0 -> 1.

Constraints

  • The number of nodes in each list is in the range [1, 100].
  • 0 <= Node.val <= 9
  • Each list represents a number without leading zeros (except the value 0).
  • The combined result can exceed 10^30, so process it digit by digit rather than as a native integer.

After the pattern

Now solve one you haven't seen.

Odometer Tape Sum is our own problem on the technique behind Add Two Numbers: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free