-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAddTwoNumbersII.java
104 lines (81 loc) · 2.34 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package com.hvdbs.leetcode.solution.java;
import com.hvdbs.savra.statsgenerator.CodeInfo;
import com.hvdbs.savra.statsgenerator.enums.Difficulty;
@CodeInfo(
difficulty = Difficulty.MEDIUM,
name = "Add Two Numbers II",
url = "https://leetcode.com/problems/add-two-numbers-ii/description/?envType=study-plan-v2&envId=programming-skills"
)
public class AddTwoNumbersII {
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;
}
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode cur = l1;
ListNode prev = null;
ListNode next;
while (cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
l1 = prev;
cur = l2;
prev = null;
while (cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
l2 = prev;
ListNode cur1 = l1;
ListNode cur2 = l2;
ListNode newHead = new ListNode(-1);
ListNode curNewHead = newHead;
newHead.next = curNewHead;
int memory = 0;
while (cur1 != null || cur2 != null) {
int sum1 = cur1 == null ? 0 : cur1.val;
int sum2 = cur2 == null ? 0 : cur2.val;
int sum = sum1 + sum2 + memory;
if (sum < 10) {
curNewHead.next = new ListNode(sum);
memory = 0;
} else {
curNewHead.next = new ListNode(sum % 10);
memory = 1;
}
if (cur1 != null) {
cur1 = cur1.next;
}
if (cur2 != null) {
cur2 = cur2.next;
}
curNewHead = curNewHead.next;
if (cur1 == null && cur2 == null && memory == 1) {
curNewHead.next = new ListNode(memory);
}
}
cur = newHead.next;
prev = null;
while (cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}