File tree 1 file changed +8
-13
lines changed
1 file changed +8
-13
lines changed Original file line number Diff line number Diff line change 4
4
* Difficulty: Medium
5
5
*
6
6
* 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.
9
10
*
10
11
* You may assume the two numbers do not contain any leading zero, except the number 0 itself.
11
12
*/
24
25
*/
25
26
var addTwoNumbers = function ( l1 , l2 ) {
26
27
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 ;
34
28
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 ) ;
36
32
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 ] ;
40
35
}
41
36
42
37
return result . next ;
You can’t perform that action at this time.
0 commit comments