forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
72 lines (65 loc) · 1.66 KB
/
Solution.java
File metadata and controls
72 lines (65 loc) · 1.66 KB
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
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ret = new ListNode(0);
ListNode curr = ret;
int carry = 0;
int v1, v2;
while (l1 != null || l2 != null) {
if (l1 == null) {
v1 = 0;
} else {
v1 = l1.val;
l1 = l1.next;
}
if (l2 == null) {
v2 = 0;
} else {
v2 = l2.val;
l2 = l2.next;
}
int s = v1 + v2 + carry;
carry = s / 10;
curr.next = new ListNode(s % 10);
curr = curr.next;
}
if (carry == 1) {
curr.next = new ListNode(1);
}
return ret.next;
}
public ListNode makeNumber(int n) {
ListNode ret = new ListNode(0);
ListNode curr = ret;
while (n > 0) {
ListNode e = new ListNode(n % 10);
curr.next = e;
curr = e;
n /= 10;
}
return ret.next;
}
public void printNumber(ListNode e) {
while (e != null) {
System.out.format("%d", e.val);
e = e.next;
}
System.out.format("\n");
}
public static void main(String[] args) {
Solution s = new Solution();
ListNode n1 = s.makeNumber(1);
ListNode n2 = s.makeNumber(999);
s.printNumber(n1);
s.printNumber(n2);
ListNode res = s.addTwoNumbers(n1, n2);
s.printNumber(res);
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}