Created
August 7, 2022 21:38
-
-
Save alex700/301ebae80626934067616f564cebed97 to your computer and use it in GitHub Desktop.
Add two numbers (LeetCode #2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ListNode(val, next) { | |
this.val = (val === undefined ? 0 : val); | |
this.next = (next === undefined ? null : next); | |
} | |
const addTwoNumbers = (l1, l2) => { | |
let carry = 0; | |
let result = new ListNode(-1) | |
let dummy = result; | |
while (l1 || l2 || carry) { | |
let l1Val = l1 ? l1.val : 0; | |
let l2Val = l2 ? l2.val : 0; | |
let nextDigit = (l1Val + l2Val + carry) % 10; | |
result.next = new ListNode(nextDigit) | |
result = result.next; | |
carry = Math.floor((l1Val + l2Val + carry) / 10); | |
l1 = l1 ? l1.next : null; | |
l2 = l2 ? l2.next : null; | |
} | |
return dummy.next; | |
} | |
let listNode0 = new ListNode(3) | |
let listNode1 = new ListNode(4, listNode0) | |
let listNode2 = new ListNode(2, listNode1) | |
let listNode01 = new ListNode(4) | |
let listNode11 = new ListNode(6, listNode01) | |
let listNode21 = new ListNode(5, listNode11) | |
let ResultListNode = addTwoNumbers(listNode2, listNode21); | |
let result = []; | |
while (ResultListNode.next) { | |
result.push(ResultListNode.val); | |
ResultListNode = ResultListNode.next; | |
if (ResultListNode.next === null) { | |
result.push(ResultListNode.val); | |
} | |
} | |
console.assert(result, [7,0,8]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment