File tree 1 file changed +40
-0
lines changed
leetcode/MEDIUM/Add Two Numbers
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public ListNode addTwoNumbers (ListNode l1 , ListNode l2 ) {
3
+ ListNode l3 = new ListNode ();
4
+ sum (l1 ,l2 ,l3 ,0 );
5
+ return l3 ;
6
+ }
7
+ public static void sum (ListNode l1 ,ListNode l2 ,ListNode l3 ,int c ){
8
+
9
+ if (l1 == null && l2 == null ){
10
+ l3 .val = c ;
11
+ return ;
12
+ }
13
+
14
+ int tmp ;
15
+
16
+ if (l1 == null ){
17
+ tmp = c + l2 .val ;
18
+ l2 = l2 .next ;
19
+ }
20
+ else if (l2 == null ){
21
+ tmp = c + l1 .val ;
22
+ l1 = l1 .next ;
23
+ }
24
+ else {
25
+ tmp = c +l1 .val +l2 .val ;
26
+ l1 = l1 .next ;
27
+ l2 = l2 .next ;
28
+ }
29
+
30
+ int carry = tmp /(int )10 ;
31
+ int sum = tmp - (carry *10 );
32
+ l3 .val = sum ;
33
+ if (l1 == null && l2 == null && carry == 0 ) return ;
34
+ ListNode p = new ListNode ();
35
+ l3 .next = p ;
36
+ //System.out.println(carry+" "+sum);
37
+ sum (l1 ,l2 ,p ,carry );
38
+ }
39
+
40
+ }
You can’t perform that action at this time.
0 commit comments