☰ All problems

32. Add Two Numbers

MediumLinked ListMathRecursion

Two non-negative integers are stored as linked lists l1 and l2, one decimal digit per node, with the digits in reverse order: the head holds the ones digit, the next node the tens digit, and so on. So [5,1,3] represents 315.

Return their sum as a linked list in the same reversed format.

Neither number has leading zeros, except the number 0 itself, which is the single-node list [0]. The numbers can be far longer than any built-in integer type can hold.

Example 1
Input: l1 = [5,1,3], l2 = [7,9]
Output: [2,1,4]

Explanation: 315 + 97 = 412, stored in reverse as [2,1,4].

Example 2
Input: l1 = [0], l2 = [0]
Output: [0]
Example 3
Input: l1 = [9,9,9], l2 = [1]
Output: [0,0,0,1]

Explanation: 999 + 1 = 1000: the carry creates a new most-significant digit.

Constraints

  • Each list has between 1 and 150 nodes
  • 0 <= Node.val <= 9
  • Neither list has leading zeros, except the number 0 itself
💡 Hint 1

Because the ones digits come first, you can add the lists exactly the way you add numbers on paper, from right to left.

💡 Hint 2

Walk both lists together, adding the two digits plus the carry. The new digit is sum % 10, the carry is sum / 10 rounded down.

💡 Hint 3

Keep going while either list has nodes left or there is a carry, and treat a missing digit as 0.

/**
 * Definition for singly-linked list (provided):
 * function ListNode(val, next) { this.val = val ?? 0; this.next = next ?? null; }
 *
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
function addTwoNumbers(l1, l2) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc