-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd-two-numbers.js
52 lines (47 loc) · 1014 Bytes
/
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
/**
* 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) {
var temp = 0
var sum = 0
var head = null
var prev = null
var node = null
while (l1 || l2) {
let a = 0, b = 0
if (l1) a= l1.val
if (l2) b = l2.val
sum = a + b + temp
if (sum >= 10) {
temp = 1
sum = sum - 10
} else {
temp = 0
}
if (head) {
node = new ListNode(sum)
prev.next = node
prev = prev.next
} else {
head = new ListNode(sum)
prev = head
}
l1 = l1 && l1.next
l2 = l2 && l2.next
}
if (temp === 1) {
node = new ListNode(1)
prev.next = node
prev = prev.next
}
return head
};