☰ All problems

Add Two Numbers

MediumLinked ListMathRecursion

An arbitrary-precision math library stores huge non-negative integers as singly linked lists of decimal digits, least significant digit first: the head holds the ones digit, the next node the tens digit, and so on. The number 4096 is stored as [6,9,0,4].

Given two such numbers, l1 and l2, return their sum as a linked list in the same format.

Neither input has leading zeros, except the number zero itself, which is the single node [0]. The numbers can be far too long for any built-in integer type.

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

Explanation: 4096 + 34 = 4130, stored ones digit first.

Example 2
Input: l1 = [0], l2 = [7,2]
Output: [7,2]

Explanation: 0 + 27 = 27: adding zero leaves the other number unchanged.

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

Explanation: 95 + 5 = 100: the carry ripples through both digits and creates a new one.

Constraints

  • Each list has between 1 and 150 nodes.
  • Every node holds a single digit from 0 to 9.
  • Neither number 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