-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0445-add-two-numbers-ii.js
More file actions
46 lines (38 loc) · 1.11 KB
/
0445-add-two-numbers-ii.js
File metadata and controls
46 lines (38 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Add Two Numbers II
* Time Complexity: O(N + M)
* Space Complexity: O(N + M)
*/
var addTwoNumbers = function (l1, l2) {
const stackOne = [];
const stackTwo = [];
let currentPointerOne = l1;
while (currentPointerOne) {
stackOne.push(currentPointerOne.val);
currentPointerOne = currentPointerOne.next;
}
let currentPointerTwo = l2;
while (currentPointerTwo) {
stackTwo.push(currentPointerTwo.val);
currentPointerTwo = currentPointerTwo.next;
}
let currentCarry = 0;
let resultingHead = null;
while (stackOne.length > 0 || stackTwo.length > 0 || currentCarry > 0) {
let digitValueOne = 0;
if (stackOne.length > 0) {
digitValueOne = stackOne.pop();
}
let digitValueTwo = 0;
if (stackTwo.length > 0) {
digitValueTwo = stackTwo.pop();
}
let combinedSum = digitValueOne + digitValueTwo + currentCarry;
currentCarry = Math.floor(combinedSum / 10);
let currentDigit = combinedSum % 10;
let newResultNode = new ListNode(currentDigit);
newResultNode.next = resultingHead;
resultingHead = newResultNode;
}
return resultingHead;
};