Skip to content

Commit 901263d

Browse files
authored
Update 2-add-two-numbers.js
1 parent 40b5c6e commit 901263d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

2-add-two-numbers.js

+42
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,45 @@ function single(l1, l2, res) {
7676
}
7777
}
7878
}
79+
80+
// another
81+
82+
/**
83+
* Definition for singly-linked list.
84+
* function ListNode(val, next) {
85+
* this.val = (val===undefined ? 0 : val)
86+
* this.next = (next===undefined ? null : next)
87+
* }
88+
*/
89+
/**
90+
* @param {ListNode} l1
91+
* @param {ListNode} l2
92+
* @return {ListNode}
93+
*/
94+
const addTwoNumbers = function(l1, l2) {
95+
let extra = false
96+
const dummy = new ListNode()
97+
let cur = dummy
98+
while(l1 || l2) {
99+
let val = 0
100+
if(l1) val += l1.val
101+
if(l2) val += l2.val
102+
if(extra) val += 1
103+
104+
if(val > 9) {
105+
extra = true
106+
val = val % 10
107+
} else {
108+
extra = false
109+
}
110+
cur.next = new ListNode(val)
111+
cur = cur.next
112+
if(l1) l1 = l1.next
113+
if(l2) l2 = l2.next
114+
}
115+
116+
if(extra) cur.next = new ListNode(1)
117+
return dummy.next
118+
};
119+
120+

0 commit comments

Comments
 (0)