-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeetCode2.java
54 lines (50 loc) · 1.33 KB
/
LeetCode2.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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class LeetCode2 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode l3 = new ListNode();
ListNode temp = l3;
boolean carry;
while (l1 != null || l2 != null) {
int tempL1 = l1 != null ? l1.val : 0;
int tempL2 = l2 != null ? l2.val : 0;
int tempSum = temp.val;
tempSum += tempL1 + tempL2;
carry = tempSum > 9;
temp.val = tempSum % 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
if (l1 != null || l2 != null || carry) {
temp.next = new ListNode();
temp.next.val = carry ? 1 : 0;
}
temp = temp.next;
}
return l3;
}
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
}