-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL2.java
More file actions
41 lines (40 loc) · 1.36 KB
/
L2.java
File metadata and controls
41 lines (40 loc) · 1.36 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
class Solution2 {
class Solution {
/**
* 2. Add Two Numbers https://leetcode.com/problems/add-two-numbers/description/
*
* @param l1
* @param l2
* @return
* @timeComplexity O(n)
* @spaceComplexity O(1)
*/
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
addHelper(head, 0, l1, l2);
return head.next;
}
private void addHelper(ListNode cur, int carry, ListNode l1, ListNode l2) {
if (l1 == null && l2 == null && carry > 0) {
ListNode newNode = new ListNode(carry);
cur.next = newNode;
} else if (l1 == null) {
if (carry == 0) {
cur.next = l2;
} else {
addHelper(cur, 0, new ListNode(carry), l2);
}
} else if (l2 == null) {
if (carry == 0) {
cur.next = l1;
} else {
addHelper(cur, 0, l1, new ListNode(carry));
}
} else {
ListNode newNode = new ListNode((l1.val + l2.val + carry) % 10);
cur.next = newNode;
addHelper(newNode, (l1.val + l2.val + carry) / 10, l1.next, l2.next);
}
}
}
}