Last active
February 17, 2019 12:43
-
-
Save lastgleam/4b1b7288df51991f7fdab4a08c7df4da to your computer and use it in GitHub Desktop.
LeetCode : Add Two Numbers
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
/** | |
* Definition for singly-linked list. | |
* function ListNode(val) { | |
* this.val = val; | |
* this.next = null; | |
* } | |
*/ | |
/** | |
* @param {ListNode} l1 | |
* @param {ListNode} l2 | |
* @return {ListNode} | |
*/ | |
var addTwoNumbers = function(l1, l2) { | |
let firstNode = null; | |
let prevNode = null; | |
let plus = 0; | |
while (l1 || l2 || plus > 0) { | |
if(!l1) { | |
l1 = new ListNode(0); | |
} | |
if (!l2) { | |
l2 = new ListNode(0); | |
} | |
let nowVal = (l1.val + l2.val + plus); | |
if (nowVal - 10 >= 0) { | |
nowVal -= 10; | |
plus = 1; | |
} else { | |
plus = 0; | |
} | |
const newNode = new ListNode(nowVal); | |
if (!firstNode) { | |
firstNode = newNode; | |
prevNode = firstNode; | |
} else { | |
prevNode.next = newNode; | |
prevNode = newNode; | |
} | |
l1 = l1.next; | |
l2 = l2.next; | |
} | |
return firstNode; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment