File tree 1 file changed +51
-0
lines changed
1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 5
5
* this.next = (next===undefined ? null : next)
6
6
* }
7
7
*/
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
+
8
59
/**
9
60
* @param {ListNode } l1
10
61
* @param {ListNode } l2
You can’t perform that action at this time.
0 commit comments