-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode2.java
54 lines (46 loc) · 1.25 KB
/
LeetCode2.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
package me.hackhub.leetcode.solution;
import me.hackhub.leetcode.structure.ListNode;
/**
* Copyright © 2017~2021 by hackhub.me
*
* @Author: mesondzh
* @Date: 2021-08-29 0:11
* @Description: https://leetcode-cn.com/problems/add-two-numbers/
*/
public class LeetCode2 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
int carry = 0;
ListNode point = new ListNode();
ListNode result;
result = point;
addNums(l1, l2, carry, point);
if (result.next == null) {
return result;
}
return result.next;
}
private void addNums(ListNode l1, ListNode l2, int carry, ListNode point) {
// 结束条件
if (l1 == null && l2 == null) {
if (carry > 0) {
point.next = new ListNode(carry);
}
return;
}
// 计算当前值
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
carry = sum / 10;
int currentVal = sum % 10;
point.next = new ListNode(currentVal);
// 递归
addNums(l1, l2, carry, point.next);
}
}