-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAddTwoNumbers.java
68 lines (62 loc) · 1.68 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
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.ListNode;
// https://leetcode.com/problems/add-two-numbers/
public class AddTwoNumbers {
private ListNode l1;
private ListNode l2;
public AddTwoNumbers(ListNode l1, ListNode l2) {
this.l1 = l1;
this.l2 = l2;
}
public ListNode solution() {
ListNode sum = new ListNode();
ListNode p = sum;
int add = 0;
while (l1 != null && l2 != null) {
int a = l1.val;
int b = l2.val;
int s = a + b + add;
if (s > 9) {
s -= 10;
add = 1;
} else {
add = 0;
}
p.next = new ListNode(s);
p = p.next;
l1 = l1.next;
l2 = l2.next;
}
if (l1 != null) {
while (l1 != null) {
int s = l1.val + add;
if (s > 9) {
s -= 10;
add = 1;
} else {
add = 0;
}
p.next = new ListNode(s);
p = p.next;
l1 = l1.next;
}
} else if (l2 != null) {
while (l2 != null) {
int s = l2.val + add;
if (s > 9) {
s -= 10;
add = 1;
} else {
add = 0;
}
p.next = new ListNode(s);
p = p.next;
l2 = l2.next;
}
}
if (add == 1) {
p.next = new ListNode(1);
}
return sum.next;
}
}