- Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathAddTwoNumbers2.java
More file actions
Latest commit
68 lines (60 loc) · 1.95 KB
/
Copy pathAddTwoNumbers2.java
File metadata and controls
68 lines (60 loc) · 1.95 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
57
58
59
60
61
62
63
64
65
66
67
68
/**
* You are given two non-empty linked lists representing two non-negative
* integers. The digits are stored in reverse order and each of their nodes
* contain a single digit. Add the two numbers and return it as a linked list.
*
* You may assume the two numbers do not contain any leading zero, except the
* number 0 itself.
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
*/
publicclassAddTwoNumbers2 {
publicListNodeaddTwoNumbers(ListNodel1, ListNodel2) {
ListNodedummy = newListNode(0);
ListNodep = dummy;
intcarry = 0;
while (l1 != null || l2 != null) {
inta = l1 == null ? 0 : l1.val;
intb = l2 == null ? 0 : l2.val;
intsum = a + b + carry;
ListNoden = newListNode(sum%10);
p.next = n;
p = p.next;
carry = sum/10;
l1 = l1 == null ? null : l1.next;
l2 = l2 == null ? null : l2.next;
}
if (carry != 0) p.next = newListNode(carry);
returndummy.next;
}
publicListNodeaddTwoNumbers2(ListNodel1, ListNodel2) {
ListNodedummy = newListNode(0);
ListNodep = dummy;
intcarry = 0;
while (l1 != null && l2 != null) {
intsum = l1.val + l2.val + carry;
p.next = newListNode(sum % 10);
p = p.next;
carry = sum / 10;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
intsum = l1.val + carry;
p.next = newListNode(sum % 10);
p = p.next;
carry = sum / 10;
l1 = l1.next;
}
while (l2 != null) {
intsum = l2.val + carry;
p.next = newListNode(sum % 10);
p = p.next;
carry = sum / 10;
l2 = l2.next;
}
if (carry != 0) p.next = newListNode(carry);
returndummy.next;
}
}