File tree 2 files changed +44
-0
lines changed
2 files changed +44
-0
lines changed Original file line number Diff line number Diff line change 7
7
| #| Title| Difficulty|
8
8
| :---| :---| :---|
9
9
1|[ Two Sum] ( ./0001-two-sum.js ) |Easy|
10
+ 2|[ Add Two Numbers] ( ./0002-add-two-numbers.js ) |Medium|
10
11
4|[ Median of Two Sorted Arrays] ( ./0004-median-of-two-sorted-arrays.js ) |Hard|
11
12
7|[ Reverse Integer] ( ./0007-reverse-integer.js ) |Easy|
12
13
27|[ Remove Element] ( ./0027-remove-element.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 2. Add Two Numbers
3
+ * https://leetcode.com/problems/add-two-numbers/
4
+ * Difficulty: Medium
5
+ *
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.
9
+ *
10
+ * You may assume the two numbers do not contain any leading zero, except the number 0 itself.
11
+ */
12
+
13
+ /**
14
+ * Definition for singly-linked list.
15
+ * function ListNode(val, next) {
16
+ * this.val = (val===undefined ? 0 : val)
17
+ * this.next = (next===undefined ? null : next)
18
+ * }
19
+ */
20
+ /**
21
+ * @param {ListNode } l1
22
+ * @param {ListNode } l2
23
+ * @return {ListNode }
24
+ */
25
+ var addTwoNumbers = function ( l1 , l2 ) {
26
+ 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
+
35
+ tail . next = new ListNode ( v % 10 ) ;
36
+ tail = tail . next ;
37
+ carry = v >= 10 ? 1 : 0 ;
38
+ l1 = l1 && l1 . next ;
39
+ l2 = l2 && l2 . next ;
40
+ }
41
+
42
+ return result . next ;
43
+ } ;
You can’t perform that action at this time.
0 commit comments