-
Notifications
You must be signed in to change notification settings - Fork 0
/
AddTwoNumbersII.java
60 lines (53 loc) · 1.31 KB
/
AddTwoNumbersII.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
59
60
package linkedlist;
import linkedlist.LinkedListTest.ListNode;
/**
* @author Shogo Akiyama
* Solved on 06/14/2019
*
* 445. Add Two Numbers II
* https://leetcode.com/problems/add-two-numbers-ii/
* Difficulty: Medium
*
* Approach: Recursion & Reverse
* Runtime: 2 ms, faster than 99.95% of Java online submissions for Add Two Numbers II.
* Memory Usage: 44.2 MB, less than 75.99% of Java online submissions for Add Two Numbers II.
*
* @see LinkedListTest#testAddTwoNumbersII()
*/
public class AddTwoNumbersII {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode r1 = reverse(l1);
ListNode r2 = reverse(l2);
helper(r1, r2, 0);
return reverse(r1);
}
ListNode reverse(ListNode n) {
ListNode prev = null;
ListNode curr = n;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
void helper(ListNode n1, ListNode n2, int carried) {
int newVal = n1.val + n2.val + carried;
int carryOver = newVal / 10;
n1.val = newVal % 10;
if (n1.next == null & n2.next == null) {
if (carryOver > 0) {
n1.next = new ListNode(carryOver);
}
return;
}
if (n1.next == null) {
n1.next = new ListNode(0);
}
if (n2.next == null) {
n2.next = new ListNode(0);
}
helper(n1.next, n2.next, carryOver);
}
}