File tree 1 file changed +39
-0
lines changed
1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ // https://leetcode.com/problems/add-two-numbers/
2
+ // T: O(max(|l1|, |l2|))
3
+ // S: O(max(|l1|, |l2|))
4
+
5
+ const addTwoNumbers = ( l1 , l2 ) => {
6
+ let p1 = l1 ;
7
+ let p2 = l2 ;
8
+ let carry = 0 ;
9
+ let result_node = new ListNode ( - 1 ) ;
10
+ let pointer = result_node ;
11
+ while ( p1 || p2 || carry !== 0 ) {
12
+ let sum = 0 ;
13
+ if ( p1 !== null && p2 !== null ) {
14
+ sum = p1 . val + p2 . val ;
15
+ p1 = p1 . next ;
16
+ p2 = p2 . next ;
17
+ } else if ( p1 !== null ) {
18
+ sum = p1 . val ;
19
+ p1 = p1 . next ;
20
+ } else if ( p2 !== null ) {
21
+ sum = p2 . val ;
22
+ p2 = p2 . next ;
23
+ }
24
+
25
+ if ( carry !== 0 ) {
26
+ sum = sum + carry ;
27
+ carry = 0 ;
28
+ }
29
+
30
+ if ( sum > 9 ) {
31
+ carry = Math . floor ( sum / 10 ) ;
32
+ sum = sum % 10 ;
33
+ }
34
+
35
+ pointer . next = new ListNode ( sum ) ;
36
+ pointer = pointer . next ;
37
+ }
38
+ return result_node . next ;
39
+ } ;
You can’t perform that action at this time.
0 commit comments