-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy path2 - Add Two Numbers.java
More file actions
44 lines (44 loc) · 1.15 KB
/
2 - Add Two Numbers.java
File metadata and controls
44 lines (44 loc) · 1.15 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int bit = 0;
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while (l1 != null && l2 != null) {
int ans = l1.val + l2.val + bit;
bit = ans / 10;
ans = ans % 10;
head.next = new ListNode(ans);
head = head.next;
l1 = l1.next;
l2 = l2.next;
}
while (l1 != null) {
int ans = l1.val + bit;
bit = ans / 10;
ans = ans % 10;
head.next = new ListNode(ans);
head = head.next;
l1 = l1.next;
}
while (l2 != null) {
int ans = l2.val + bit;
bit = ans / 10;
ans = ans % 10;
head.next = new ListNode(ans);
head = head.next;
l2 = l2.next;
}
if (bit != 0) {
head.next = new ListNode(bit);
}
return dummy.next;
}
}