-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution2.java
More file actions
56 lines (50 loc) · 1.52 KB
/
Copy pathSolution2.java
File metadata and controls
56 lines (50 loc) · 1.52 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
package medium;
public class Solution2 {
private static String toString(ListNode node) {
StringBuilder builder = new StringBuilder();
while (node != null) {
builder.append(node.val);
node = node.next;
}
return builder.toString();
}
private static ListNode getNode(int[] list) {
ListNode root = new ListNode(0), temp = root;
for (int i : list) {
temp = temp.next = new ListNode(i);
}
return root.next;
}
public static void main(String[] args) {
int[][] cases = {
{2, 4, 3},
{5, 6, 4}
};
Solution2 solution = new Solution2();
int i = 0;
while (i < cases.length) {
ListNode l1 = getNode(cases[i++]);
ListNode l2 = getNode(cases[i++]);
System.out.println(toString(solution.addTwoNumbers(l1, l2)));
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int sum = 0;
ListNode root = new ListNode(0), temp = root;
while (true) {
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
if (l1 != null || l2 != null || sum != 0) {
temp = temp.next = new ListNode(sum % 10);
sum /= 10;
} else break;
}
return root.next == null ? root : root.next;
}
}