Skip to content

Commit 27b72f9

Browse files
committed
萤火虫-N2
1 parent d38567f commit 27b72f9

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

src/main/java/N1_100/N2.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package N1_100;
2+
3+
import common.ListNode;
4+
5+
public class N2 {
6+
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
7+
// 先加起来,不处理进位
8+
ListNode result = addIgnoreCarry(l1, l2);
9+
carry(result);
10+
return result;
11+
}
12+
13+
// 直接相加,忽略进位
14+
private ListNode addIgnoreCarry(ListNode l1, ListNode l2) {
15+
ListNode head = new ListNode(l1.val + l2.val);
16+
ListNode result = head;
17+
l1 = l1.next;
18+
l2 = l2.next;
19+
while (l1 != null && l2 != null) {
20+
head.next = new ListNode(l1.val + l2.val);
21+
l1 = l1.next;
22+
l2 = l2.next;
23+
head = head.next;
24+
}
25+
if (l1 != null) {
26+
head.next = l1;
27+
} else if (l2 != null) {
28+
head.next = l2;
29+
}
30+
return result;
31+
}
32+
33+
// 处理进位
34+
private void carry(ListNode listNode) {
35+
boolean needCarry = false; // 当前是否需要进位
36+
while (listNode != null) {
37+
int val = listNode.val;
38+
if (needCarry) {
39+
val += 1;
40+
}
41+
if (val >= 10) {
42+
listNode.val = val % 10;
43+
needCarry = true;
44+
if (listNode.next == null) {
45+
listNode.next = new ListNode(1);
46+
break;
47+
}
48+
} else {
49+
listNode.val = val;
50+
needCarry = false;
51+
}
52+
listNode = listNode.next;
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)