-
Notifications
You must be signed in to change notification settings - Fork 1
/
AddTwoNumbers.java
99 lines (92 loc) · 2.81 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import java.util.ArrayDeque;
/**
* Use Elementary Math to solve the problem. attention:
*
* <p>1. Use dummy head when using LinkNode. It's convenient because you don't need to judge whether it's head.
* <p>2. Simplify your code. (when l1 is null or l2 is null, use 0 to substitute!)
* <p>3. judge whether carry is 1 when it ends.
*
* @author LBW
*/
public class AddTwoNumbers {
/**
* this is my initial version
*/
@SuppressWarnings("Duplicates")
@Deprecated
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, current = null;
int carry = 0;
while (l1 != null && l2 != null) {
int val1 = l1.val;
int val2 = l2.val;
int sum = val1 + val2 + carry;
if (sum >= 10)
carry = 1;
else
carry = 0;
if (head == null) {
head = new ListNode(sum % 10);
current = head;
}
else {
current.next = new ListNode(sum % 10);
current = current.next;
}
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
int sum = l1.val + carry;
if (sum >= 10)
carry = 1;
else
carry = 0;
current.next = new ListNode(sum % 10);
current = current.next;
l1 = l1.next;
}
while (l2 != null) {
int sum = l2.val + carry;
if (sum >= 10)
carry = 1;
else
carry = 0;
current.next = new ListNode(sum % 10);
current = current.next;
l2 = l2.next;
}
// if still has carry. like 5+5=10
if (carry == 1)
current.next = new ListNode(1);
return head;
}
/**
* this is referenced by standard solution.
*/
public ListNode standardAddTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode current = dummyHead;
int carry = 0;
while (l1 != null || l2 != null) {
int p = l1 != null ? l1.val : 0;
int q = l2 != null ? l2.val : 0;
int sum = p + q + carry;
carry = sum / 10;
current.next = new ListNode(sum % 10);
current = current.next;
if (l1 != null)
l1 = l1.next;
if (l2 != null)
l2 = l2.next;
}
if (carry == 1)
current.next = new ListNode(1);
return dummyHead.next;
}
public static void main(String[] args) {
AddTwoNumbers addTwoNumbers = new AddTwoNumbers();
addTwoNumbers.addTwoNumbers(null, null);
addTwoNumbers.standardAddTwoNumbers(null, null);
}
}