-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-two-numbers.js
99 lines (78 loc) · 1.63 KB
/
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* 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}
*/
var addTwoNumbers = function (l1, l2) {
let head, tail
// 表示进位
let carry = 0
while (l1 || l2) {
const n1 = l1 ? l1.val : 0
const n2 = l2 ? l2.val : 0
const sum = n1 + n2 + carry
carry = Math.floor(sum / 10)
// 当前数值
const curr = sum % 10
if (!head) {
head = tail = new ListNode(curr)
} else {
tail.next = new ListNode(curr)
tail = tail.next
}
if (l1) {
l1 = l1.next
}
if (l2) {
l2 = l2.next
}
}
// 如果最后的进位大于0
if (carry > 0) {
tail.next = new ListNode(carry)
}
return head
};
// ----- 方法二 (BigInt取巧) ------- //
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var addTwoNumbers = function (l1, l2) {
let aResult = [], bResult = []
while (l1 || l2) {
if (l1) {
aResult.push(l1.val)
l1 = l1.next
}
if (l2) {
bResult.push(l2.val)
l2 = l2.next
}
}
aResult = BigInt(aResult.reverse().join(''))
bResult = BigInt(bResult.reverse().join(''))
let sum = aResult + bResult
let head = null
if (sum === 0) {
return new ListNode(sum)
}
sum.toString().split('').forEach(num => {
num = Number(num)
if (!head) {
head = new ListNode(num)
} else {
head = new ListNode(num, head)
}
})
return head
};