-
Notifications
You must be signed in to change notification settings - Fork 2
/
AddTwoNumbers.java
36 lines (30 loc) · 1.04 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
package leetcode.list;
import leetcode.helpers.ListNode;
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode result = new ListNode(0);
ListNode current = result;
int carry = 0;
while (l1 != null || l2 != null) {
if (l1 != null && l2 != null) {
current.next = new ListNode((l1.val + l2.val + carry) % 10);
carry = (l1.val + l2.val + carry) / 10;
l1 = l1.next;
l2 = l2.next;
} else if (l1 != null) {
current.next = new ListNode((l1.val + carry) % 10);
carry = (l1.val + carry) / 10;
l1 = l1.next;
} else {
current.next = new ListNode((l2.val + carry) % 10);
carry = (l2.val + carry) / 10;
l2 = l2.next;
}
current = current.next;
}
if (carry != 0) {
current.next = new ListNode(carry);
}
return result.next;
}
}