Add Two Numbers II
Medium · linked list
Two non-negative whole numbers are written as linked lists, one digit per node, with the most significant digit first. For example, the number 7243 is the list [7, 2, 4, 3].
Add the two numbers and return the sum in the same form: a linked list with one digit per node, most significant digit first. The two numbers can have a different number of digits, and the sum can have one more digit than the longer input.
Neither number has leading zeros, except for the number 0 itself, which is a single node. The sum must not have leading zeros either.
The nodes you receive are ListNode objects with a val and a next.
Examples
Example 1
Input: l1 = [7, 2, 4, 3], l2 = [5, 6, 4]
Output: [7, 8, 0, 7]
7243 + 564 = 7807.
Example 2
Input: l1 = [5], l2 = [5]
Output: [1, 0]
5 + 5 = 10, which has one more digit than either input.
Example 3
Input: l1 = [0], l2 = [0]
Output: [0]
Constraints
- 1 <= number of nodes in each list <= 1000
- 0 <= Node.val <= 9
- Neither number has leading zeros, except the number 0 itself.