-
Notifications
You must be signed in to change notification settings - Fork 0
/
Add Two Numbers.java
41 lines (41 loc) · 994 Bytes
/
Add Two Numbers.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
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode d = new ListNode();
ListNode cur = d;
int carry = 0;
while (l1 != null && l2 != null) {
int sum = l1.val + l2.val + carry;
int dig = sum % 10;
carry = sum / 10;
ListNode node = new ListNode(dig);
cur.next = node;
l1 = l1.next;
l2 = l2.next;
cur = cur.next;
}
while (l1 != null) {
int sum = l1.val + carry;
int dig = sum % 10;
carry = sum / 10;
ListNode node = new ListNode(dig);
cur.next = node;
l1 = l1.next;
cur = cur.next;
}
while (l2 != null) {
int sum = l2.val + carry;
int dig = sum % 10;
carry = sum / 10;
ListNode node = new ListNode(dig);
cur.next = node;
l2 = l2.next;
cur = cur.next;
}
if (carry == 0) {
return d.next;
}
ListNode node = new ListNode(carry);
cur.next = node;
return d.next;
}
}