/2. Add Two Numbers

2. Add Two Numbers

Medium
Linked Lists48.1% acceptance

Given two singly linked lists, each representing a non-negative integer in reverse digit order (least significant digit first), compute their sum and return the result as a singly linked list in the same reverse digit order. Each node contains a single digit (0-9).

Example 1

Input: node_a = ListNode(1, ListNode(2, ListNode(3))) node_b = ListNode(9, ListNode(8, ListNode(7)))

Output: ListNode(0, ListNode(1, ListNode(1, ListNode(1))))

Explanation: 321 + 789 = 1110, so output is [0,1,1,1]

Example 2

Input: node_a = ListNode(5) node_b = ListNode(5)

Output: ListNode(0, ListNode(1))

Explanation: 5 + 5 = 10, so output is [0,1]

Example 3

Input: node_a = ListNode(4, ListNode(3)) node_b = ListNode(6)

Output: ListNode(0, ListNode(4))

Explanation: 34 + 6 = 40, so output is [0,4]

Constraints

  • 1 <= length of node_a <= 100
  • 1 <= length of node_b <= 100
  • 0 <= node_a.val <= 9 for each node
  • 0 <= node_b.val <= 9 for each node
  • Neither list contains leading zeros except for the number 0 itself
Python (current runtime)

Case 1

Input: node_a = ListNode(2, ListNode(1)) node_b = ListNode(8, ListNode(9))

Expected: ListNode(0, ListNode(1, ListNode(1)))

Case 2

Input: node_a = ListNode(7, ListNode(3, ListNode(2))) node_b = ListNode(5, ListNode(6))

Expected: ListNode(2, ListNode(0, ListNode(3)))

Case 3

Input: node_a = ListNode(0) node_b = ListNode(1, ListNode(0))

Expected: ListNode(1, ListNode(0))