forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0002-add-two-numbers.js
60 lines (47 loc) · 1.55 KB
/
0002-add-two-numbers.js
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* https://leetcode.com/problems/add-two-numbers/
* Time O(MAX(N, M)) | Space O(MAX(N, M))
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2) {
let sentinel = tail = new ListNode();
return add(l1, l2, tail, sentinel); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */
}
const add = (l1, l2, tail, sentinel, carry = 0) => {
const isBaseCase = !(l1 || l2 || carry);
if (isBaseCase) return sentinel.next;
return dfs(l1, l2, tail, sentinel, carry);/* Time O(MAX(N, M)) | Space O(MAX(N, M)) */
}
const dfs = (l1, l2, tail, sentinel, carry) => {
const sum = (l1?.val || 0) + (l2?.val || 0) + carry;
const val = sum % 10;
carry = Math.floor(sum / 10);
tail.next = new ListNode(val);
tail = tail.next;
l1 = l1?.next || null;
l2 = l2?.next || null;
add(l1, l2, tail, sentinel, carry); /* Time O(MAX(N, M)) | Space O(MAX(N, M)) */
return sentinel.next;
}
/**
* https://leetcode.com/problems/add-two-numbers/
* Time O(MAX(N, M)) | Space O(MAX(N, M))
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function(l1, l2, carry = 0) {
let sentinel = tail = new ListNode();
while (l1 || l2 || carry) {/* Time O(MAX(N, M)) */
const sum = (l1?.val || 0) + (l2?.val || 0) + carry;
const val = sum % 10;
carry = Math.floor(sum / 10);
tail.next = new ListNode(val);
tail = tail.next;
l1 = l1?.next || null;
l2 = l2?.next || null;
}
return sentinel.next;
};