-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
48 lines (41 loc) · 828 Bytes
/
index.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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
const addTwoNumbers = function (l1, l2) {
const List = new ListNode(0);
let head = List;
let sum = 0;
let carry = 0;
while (l1 !== null || l2 !== null || sum > 0) {
if (l1 !== null) {
sum = sum + l1.val;
l1 = l1.next;
}
if (l2 !== null) {
sum = sum + l2.val;
l2 = l2.next;
}
if (sum >= 10) {
carry = 1;
sum = sum - 10;
}
head.next = new ListNode(sum);
head = head.next;
sum = carry;
carry = 0;
}
return List.next;
};
/**
* Runtime: 154 ms
* Memory Usage: 46.7 MB
**/