-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2 Add Two Numbers.js
More file actions
53 lines (47 loc) · 1.07 KB
/
2 Add Two Numbers.js
File metadata and controls
53 lines (47 loc) · 1.07 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
47
48
49
50
51
52
53
/**
* 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) {
if (l1 === null) {
return l2;
} else if (l2 === null) {
return l1;
}
var head = l1;
var temp = l1.val + l2.val;
var needPlus = 0;
head.val = temp % 10;
if (temp >= 10) {
needPlus = 1;
}
l1 = l1.next;
l2 = l2.next;
var current = head;
while (l1 !== null || l2 !== null) {
current.next = l1 ? l1 : l2;
current = current.next;
temp = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + needPlus;
current.val = temp % 10;
if (temp >= 10) {
needPlus = 1;
} else {
needPlus = 0;
}
l1 = l1 ? l1.next : null;
l2 = l2 ? l2.next : null;
}
if (needPlus) {
var newnode = new ListNode(1);
current.next = newnode;
}
return head;
};