Created
August 16, 2019 09:10
Star
You must be signed in to star a gist
"Add Two Numbers" leetcode coding interview problem & solution
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) { | |
this.val = val; | |
this.next = null; | |
} | |
/** | |
* @param {ListNode} l1 | |
* @param {ListNode} l2 | |
* @return {ListNode} | |
*/ | |
var addTwoNumbers = function(l1, l2) { | |
let carry = 0; | |
let returnNode = null; | |
let lastNode = null; | |
while (l1 || l2 || carry > 0) { | |
let sum = carry; | |
if(l1) { | |
sum = sum + l1.val; | |
l1 = l1.next; | |
} | |
if(l2) { | |
sum = sum + l2.val; | |
l2 = l2.next; | |
} | |
let temp = new ListNode(sum % 10) | |
carry = Math.floor(sum / 10) | |
if (lastNode == null) { | |
lastNode = temp; | |
returnNode = lastNode; | |
} else { | |
lastNode.next = temp; | |
lastNode = lastNode.next; | |
} | |
} | |
return returnNode; | |
}; | |
let l1 = new ListNode(2); | |
let l11 = new ListNode(4); | |
l1.next = l11; | |
let l2 = new ListNode(5); | |
let l21 = new ListNode(6); | |
l2.next = l21; | |
let l22 = new ListNode(4); | |
l21.next = l22; | |
let result = addTwoNumbers(l1, l2); | |
while (result) { | |
console.log(result.val); | |
result = result.next; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment