-
Notifications
You must be signed in to change notification settings - Fork 2
/
Que2.java
60 lines (45 loc) · 1.16 KB
/
Que2.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
import java.util.ArrayList;
import java.util.List;
/**
* @Author: Han-YLun
* @date 2019/5/11 0011
* @Version 1.0
*/
public class Que2 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode curNode = null;
ListNode result = null;
boolean carryBit = false;
while (l1 != null || l2 != null){
int a = 0,
b = 0;
if (l1 != null){
a = l1.val;
l1 = l1.next;
}
if (l2 != null){
b = l2.val;
l2 = l2.next;
}
int sum = (carryBit ? 1 : 0) + a +b;
int value = sum%10;
carryBit = sum >= 10;
if (result == null){
result = new ListNode(value);
curNode = result;
}else{
curNode.next = new ListNode(value);
curNode = curNode.next;
}
}
if (carryBit){
curNode.next = new ListNode(1);
}
return result;
}
}