|
| 1 | +// From LeetCode |
| 2 | + |
| 3 | +// You are given two non-empty linked lists representing two non-negative integers. |
| 4 | +// The digits are stored in reverse order and each of their nodes contain a single digit. |
| 5 | +// Add the two numbers and return it as a linked list. |
| 6 | + |
| 7 | +// You may assume the two numbers do not contain any leading zero, except the number 0 itself. |
| 8 | + |
| 9 | +// @param {ListNode} l1 |
| 10 | +// @param {ListNode} l2 |
| 11 | +// @return {ListNode} |
| 12 | + |
| 13 | +function ListNode(val, next) { |
| 14 | + this.val = val === undefined ? 0 : val; |
| 15 | + this.next = next === undefined ? null : next; |
| 16 | +} |
| 17 | + |
| 18 | +// Create Linked lists from numbers |
| 19 | + |
| 20 | +createLinkedListNumber = function (number) { |
| 21 | + const remainder = number % 10; |
| 22 | + const division = Math.floor(number / 10); |
| 23 | + if (division !== 0) { |
| 24 | + return new ListNode(remainder, createLinkedListNumber(division)); |
| 25 | + } else { |
| 26 | + return new ListNode(remainder, undefined); |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +printLinkedListNumber = function (linkedListNumber) { |
| 31 | + let num = linkedListNumber; |
| 32 | + let nextNum = num.next; |
| 33 | + |
| 34 | + while (true) { |
| 35 | + console.log(num.val); |
| 36 | + |
| 37 | + if (nextNum === null) { |
| 38 | + break; |
| 39 | + } |
| 40 | + num = nextNum; |
| 41 | + nextNum = num.next; |
| 42 | + } |
| 43 | +}; |
| 44 | + |
| 45 | +// Solution ///////////////////////// |
| 46 | +var addTwoNumbers = function (l1, l2, carryover = 0) { |
| 47 | + console.log(`Carryover is: ${carryover}`); |
| 48 | + if (l1 === null && l2 === null) { |
| 49 | + if (carryover === 1) { |
| 50 | + return new ListNode(1, null); |
| 51 | + } |
| 52 | + return null; |
| 53 | + } else if (l1 === null) { |
| 54 | + if (l2.val + carryover >= 10) { |
| 55 | + return new ListNode( |
| 56 | + (l2.val + carryover) % 10, |
| 57 | + addTwoNumbers(null, l2.next, 1) |
| 58 | + ); |
| 59 | + } |
| 60 | + return new ListNode(l2.val + carryover, addTwoNumbers(null, l2.next)); |
| 61 | + } else if (l2 === null) { |
| 62 | + if (l1.val + carryover >= 10) { |
| 63 | + return new ListNode( |
| 64 | + (l1.val + carryover) % 10, |
| 65 | + addTwoNumbers(l1.next, null, 1) |
| 66 | + ); |
| 67 | + } |
| 68 | + return new ListNode(l1.val + carryover, addTwoNumbers(l1.next, null)); |
| 69 | + } else { |
| 70 | + const sum = l1.val + l2.val + carryover; |
| 71 | + if (sum >= 10) { |
| 72 | + return new ListNode(sum % 10, addTwoNumbers(l1.next, l2.next, 1)); |
| 73 | + } |
| 74 | + return new ListNode(sum, addTwoNumbers(l1.next, l2.next)); |
| 75 | + } |
| 76 | +}; |
| 77 | + |
| 78 | +const linkedListNumber1 = createLinkedListNumber(999); |
| 79 | +const linkedListNumber2 = createLinkedListNumber(1); |
| 80 | + |
| 81 | +printLinkedListNumber(addTwoNumbers(linkedListNumber1, linkedListNumber2)); |
0 commit comments