|
| 1 | +/** |
| 2 | +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. |
| 3 | +
|
| 4 | +You may assume the two numbers do not contain any leading zero, except the number 0 itself. |
| 5 | +
|
| 6 | +Example 1: |
| 7 | +Input: l1 = [2,4,3], l2 = [5,6,4] |
| 8 | +Output: [7,0,8] |
| 9 | +Explanation: 342 + 465 = 807. |
| 10 | +
|
| 11 | +Example 2: |
| 12 | +Input: l1 = [0], l2 = [0] |
| 13 | +Output: [0] |
| 14 | +Example 3: |
| 15 | +
|
| 16 | +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] |
| 17 | +Output: [8,9,9,9,0,0,0,1] |
| 18 | + |
| 19 | +Constraints: |
| 20 | +
|
| 21 | +The number of nodes in each linked list is in the range [1, 100]. |
| 22 | +0 <= Node.val <= 9 |
| 23 | +It is guaranteed that the list represents a number that does not have leading zeros. |
| 24 | +*/ |
| 25 | + |
| 26 | +class ListNode { |
| 27 | + val: number; |
| 28 | + next: ListNode | null; |
| 29 | + constructor(val?: number, next?: ListNode | null) { |
| 30 | + this.val = val === undefined ? 0 : val; |
| 31 | + this.next = next === undefined ? null : next; |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +function addTwoNumbers( |
| 36 | + l1: ListNode | null, |
| 37 | + l2: ListNode | null |
| 38 | +): ListNode | null { |
| 39 | + let current = new ListNode(0); |
| 40 | + let result = current; |
| 41 | + |
| 42 | + let carry = 0; |
| 43 | + |
| 44 | + while (l1 || l2 || carry) { |
| 45 | + let value1 = l1 ? l1.val : 0; |
| 46 | + let value2 = l2 ? l2.val : 0; |
| 47 | + |
| 48 | + let sum = value1 + value2 + carry; |
| 49 | + |
| 50 | + carry = 0; |
| 51 | + |
| 52 | + if (sum > 9) { |
| 53 | + carry = ~~(sum / 10); |
| 54 | + sum = sum % 10; |
| 55 | + } |
| 56 | + |
| 57 | + current.next = new ListNode(sum); |
| 58 | + current = current.next; |
| 59 | + |
| 60 | + if (l1) l1 = l1.next; |
| 61 | + if (l2) l2 = l2.next; |
| 62 | + } |
| 63 | + |
| 64 | + return result.next; |
| 65 | +} |
0 commit comments