「リートコード - 2. Add Two Numbers」

ジャバソリューション

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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res = new ListNode((l1.val + l2.val) % 10), tail = res;
int carry = (l1.val + l2.val) / 10;
ListNode u = l1.next, v = l2.next;
while (carry != 0 || u != null || v != null) {
int sum = carry;
if (u != null) {
sum += u.val;
u = u.next;
}
if (v != null) {
sum += v.val;
v = v.next;
}
tail.next = new ListNode(sum % 10);
tail = tail.next;
carry = sum / 10;
}
return res;
}
}

明天one-one聊promotion,紧张ing。