-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddTwoNumbers.java
133 lines (107 loc) · 2.53 KB
/
AddTwoNumbers.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package LeetCode;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class AddTwoNumbers {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode list1 , list2 , listTemp1,listTemp2 , startNew , start;
int len1=0 , len2=0 , carry=0;
list1 = l1 ; listTemp1 = l1;
list2 = l2 ; listTemp2 = l2;
while(list1 != null){
len1++;
list1 = list1.next;
}
while(list2 != null){
len2++;
list2 = list2.next;
}
if(len1 == 0 && len2 == 0)
return null;
if(len1 == 0 && len2 != 0)
return l2;
if(len2 == 0 && len1 != 0)
return l1;
int sum = listTemp1.val + listTemp2.val;
if(sum>=10){
startNew = new ListNode(sum%10);
carry = 1;
}else{
startNew = new ListNode(sum);
carry = 0;
}
start = startNew;
listTemp1 = listTemp1.next;
listTemp2 = listTemp2.next;
while(listTemp1 != null && listTemp2 != null){
sum = listTemp1.val + listTemp2.val + carry;
if(sum>=10){
startNew.next = new ListNode(sum%10);
carry = 1;
}else{
startNew.next = new ListNode(sum);
carry = 0;
}
startNew = startNew.next;
listTemp1 = listTemp1.next;
listTemp2 = listTemp2.next;
}
//now 3 conditions
if(len1 == len2){
if(carry == 1){
startNew.next = new ListNode(1);
startNew = startNew.next;
}
return start;
}
else if(len1 > len2){
while(listTemp1 != null ){
sum = listTemp1.val + carry;
if(sum>=10){
startNew.next = new ListNode(sum%10);
carry = 1;
}else{
startNew.next = new ListNode(sum);
carry = 0;
}
startNew = startNew.next;
listTemp1 = listTemp1.next;
}
}
else if(len2 > len1){
while(listTemp2 != null ){
sum = listTemp2.val + carry;
if(sum>=10){
startNew.next = new ListNode(sum%10);
carry = 1;
}else{
startNew.next = new ListNode(sum);
carry = 0;
}
startNew = startNew.next;
listTemp2 = listTemp2.next;
}
}
if(carry == 1){
startNew.next = new ListNode(1);
startNew = startNew.next;
}
return start;
}
public static void main(String[] args) {
//2 - 4 - 3
ListNode start1 = new ListNode(5);
//5 - 6 - 4 - 7 - 8
ListNode start2 = new ListNode(5);
ListNode result = addTwoNumbers(start1, start2);
while (result != null) {
System.out.print(result.val + " ");
result = result.next;
}
}
}