-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main002.java
85 lines (75 loc) · 2.09 KB
/
Main002.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
public class Main002 {
public static void main(String[] args){
new Main002().fun();
}
public void fun(){
ListNode t = new ListNode(5);
ListNode t1 = new ListNode(5);
ListNode res = addTwoNumbers(t,t1);
ListNode tt = res;
while (tt!= null){
System.out.println(tt.val);
tt = tt.next;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode tmpNode1 = l1;
ListNode tmpNode2 = l2;
ListNode t = null;
int inc = 0;
ListNode tmp = new ListNode(-1);
ListNode res = tmp;
while (tmpNode1 != null && tmpNode2 != null){
t = new ListNode(inc);
int val = tmpNode1.val + tmpNode2.val + t.val;
if (val<10){
t.val = val;
inc = 0;
}else {
t.val = val%10;
inc = val/10;
}
tmp.next = t;
tmp = tmp.next;
tmpNode1 = tmpNode1.next;
tmpNode2 = tmpNode2.next;
}
while (tmpNode1 != null){
t = new ListNode(inc);
int val = tmpNode1.val + t.val;
if (val<10){
t.val = val;
inc = 0;
}else {
t.val = val%10;
inc = val/10;
}
tmp.next = t;
tmp = tmp.next;
tmpNode1 = tmpNode1.next;
}
while (tmpNode2 != null){
t = new ListNode(inc);
int val = tmpNode2.val + t.val;
if (val<10){
t.val = val;
inc = 0;
}else {
t.val = val%10;
inc = val/10;
}
tmp.next = t;
tmp = tmp.next;
tmpNode2 = tmpNode2.next;
}
if (inc != 0){
tmp.next = new ListNode(inc);
}
return res.next;
}
class ListNode{
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}