-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathAddTwoNumbers.java
58 lines (53 loc) · 1.49 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
int carry = 0;
ListNode dummy = new ListNode(0);
while (l1 != null || l2 != null){
int sum = carry + getVal(l1) + getVal(l2);
carry = sum / 10;
ListNode current = new ListNode(sum % 10);
current.next = dummy.next;
dummy.next = current;
l1 = getNext(l1);
l2 = getNext(l2);
}
if (carry != 0){
ListNode head = new ListNode(carry);
head.next = dummy.next;
dummy.next = head;
}
return reverse(dummy.next);
}
public int getVal(ListNode node){
if (node == null) return 0;
return node.val;
}
public ListNode getNext(ListNode node){
if (node == null) return null;
return node.next;
}
public ListNode reverse(ListNode head) {
ListNode current = head;
ListNode newHead = null;
while (current != null) {
ListNode tmp = current;
current = current.next;
tmp.next = newHead;
newHead = tmp;
}
return newHead;
}
}