LeetCode | 第二题两数相加

心血来潮,重新用Java做了下之前用Python做过的题。

题目

递归解法:

Solution:

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
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null & l2 == null)
return null;
if (l1 == null)
l1 = new ListNode(0);
if (l2 == null)
l2 = new ListNode(0);
ListNode l3 = new ListNode((l1.val + l2.val) % 10, addTwoNumbers(l1.next, l2.next, l1.val + l2.val >= 10));
return l3;
}

public ListNode addTwoNumbers(ListNode l1, ListNode l2, boolean i) {
if (l1 == null & l2 == null & !i)
return null;
if (l1 == null)
l1 = new ListNode(0);
if (l2 == null)
l2 = new ListNode(0);
if (i)
return new ListNode((l1.val + l2.val + 1) % 10, addTwoNumbers(l1.next, l2.next, l1.val + l2.val + 1 >= 10));
else
return new ListNode((l1.val + l2.val) % 10, addTwoNumbers(l1.next, l2.next, l1.val + l2.val >= 10));
}
}

需要自己测试的还需要下边两个文件。

ListNode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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;
}
}

test:

1
2
3
4
5
6
7
8
9
10
11
12
public class test {
public static void main(String[] args) {
ListNode l1=new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9))))));
ListNode l2=new ListNode(9,new ListNode(9,new ListNode(9,new ListNode(9))));
Solution l=new Solution();
ListNode l3=l.addTwoNumbers(l1,l2);
while (l3!=null){
System.out.println(l3.val);
l3=l3.next;
}
}
}