Skip to content

Commit 9961cfb

Browse files
committed
Add solution #2
1 parent 3f4031c commit 9961cfb

File tree

1 file changed

+8
-13
lines changed

1 file changed

+8
-13
lines changed

solutions/0002-add-two-numbers.js

+8-13
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
* Difficulty: Medium
55
*
66
* You are given two non-empty linked lists representing two non-negative integers.
7-
* The digits are stored in reverse order, and each of their nodes contains a single
8-
* digit. Add the two numbers and return the sum as a linked list.
7+
*
8+
* The digits are stored in reverse order, and each of their nodes contains a single digit.
9+
* Add the two numbers and return the sum as a linked list.
910
*
1011
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
1112
*/
@@ -24,19 +25,13 @@
2425
*/
2526
var addTwoNumbers = function(l1, l2) {
2627
const result = new ListNode();
27-
let tail = result;
28-
let carry = 0;
29-
30-
while (l1 || l2 || carry) {
31-
const v1 = l1 ? l1.val : 0;
32-
const v2 = l2 ? l2.val : 0;
33-
const v = v1 + v2 + carry;
3428

35-
tail.next = new ListNode(v % 10);
29+
for (let tail = result, carry = 0; l1 || l2 || carry;) {
30+
const value = (l1?.val ?? 0) + (l2?.val ?? 0) + carry;
31+
tail.next = new ListNode(value % 10);
3632
tail = tail.next;
37-
carry = v >= 10 ? 1 : 0;
38-
l1 = l1 && l1.next;
39-
l2 = l2 && l2.next;
33+
carry = value >= 10 ? 1 : 0;
34+
[l1, l2] = [l1 && l1.next, l2 && l2.next];
4035
}
4136

4237
return result.next;

0 commit comments

Comments
 (0)