-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAddTwoNumbers.java
More file actions
29 lines (28 loc) · 830 Bytes
/
AddTwoNumbers.java
File metadata and controls
29 lines (28 loc) · 830 Bytes
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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class AddTwoNumbers {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummp = new ListNode(0);
ListNode tail = dummp;
int carry = 0;
while (l1 != null || l2 != null) {
int d1 = l1 == null ? 0 : l1.val;
int d2 = l2 == null ? 0 : l2.val;
int sum = d1 + d2 + carry;
int d = sum % 10;
carry = sum / 10;
tail.next = new ListNode(d);
tail = tail.next;
if (l1 != null) l1 = l1.next;
if (l2 != null) l2 = l2.next;
}
if (carry > 0) tail.next = new ListNode(carry);
return dummp.next;
}
}