Skip to content

Commit 7a467ea

Browse files
committed
Add Two Numbers (the best solution)
1 parent e9c66ee commit 7a467ea

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

algorithms/add-two-numbers.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,57 @@
55
* this.next = (next===undefined ? null : next)
66
* }
77
*/
8+
9+
10+
// ----- 方法一(最佳) ------- //
11+
12+
/**
13+
* @param {ListNode} l1
14+
* @param {ListNode} l2
15+
* @return {ListNode}
16+
*/
17+
var addTwoNumbers = function (l1, l2) {
18+
let head, tail
19+
// 表示进位
20+
let carry = 0
21+
22+
while (l1 || l2) {
23+
const n1 = l1 ? l1.val : 0
24+
const n2 = l2 ? l2.val : 0
25+
const sum = n1 + n2 + carry
26+
27+
carry = Math.floor(sum / 10)
28+
29+
// 当前数值
30+
const curr = sum % 10
31+
32+
if (!head) {
33+
head = tail = new ListNode(curr)
34+
} else {
35+
tail.next = new ListNode(curr)
36+
tail = tail.next
37+
}
38+
39+
if (l1) {
40+
l1 = l1.next
41+
}
42+
if (l2) {
43+
l2 = l2.next
44+
}
45+
}
46+
47+
// 如果最后的进位大于0
48+
if (carry > 0) {
49+
tail.next = new ListNode(carry)
50+
}
51+
52+
return head
53+
};
54+
55+
56+
57+
// ----- 方法二 (BigInt取巧) ------- //
58+
859
/**
960
* @param {ListNode} l1
1061
* @param {ListNode} l2

0 commit comments

Comments
 (0)