#20MediumLinked Lists & Math· Digit-by-Digit Addition with Carry
Add Two Numbers
Input format
l1: array of digits (least significant first), l2: array of digits (least significant first)
Output format
Array of digits of the sum, least significant first
Examples
Input: l1 = [2, 4, 3], l2 = [5, 6, 4]
Output: [7, 0, 8]
342 + 465 = 807, stored as 7 -> 0 -> 8.
Input: l1 = [9, 9, 9, 9, 9, 9, 9], l2 = [9, 9, 9, 9]
Output: [8, 9, 9, 9, 0, 0, 0, 1]
9999999 + 9999 = 10009998. The last carry creates an extra node.
Input: l1 = [5], l2 = [5]
Output: [0, 1]
5 + 5 = 10: the carry needs a new node even though both lists are finished.
Constraints
- 1 <= number of nodes in each list <= 100
- 0 <= Node.val <= 9
- Neither list has leading zeros (that is, its last node is non-zero), unless the number is 0.
Study first
- #linked-lists
- #math
- #simulation
