-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution002.java
55 lines (46 loc) · 1.22 KB
/
Solution002.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
package algorithm.leetcode;
/**
* @author mayuan
* @desc 两数相加
* 时间复杂度: O(n) 或 O(m) n,m为两个链表的长度,取最大的
* 空间复杂度: O(1)
* @date 2018/02/07
*/
public class Solution002 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode p = l1, q = l2, current = head;
int carry = 0;
while (null != p || null != q) {
int x = (null != p) ? p.val : 0;
int y = (null != q) ? q.val : 0;
int sum = carry + x + y;
if (10 <= sum) {
carry = 1;
sum -= 10;
} else {
carry = 0;
}
current.next = new ListNode(sum);
current = current.next;
if (null != p) {
p = p.next;
}
if (null != q) {
q = q.next;
}
}
// 最后一步仍然需要进位
if (0 < carry) {
current.next = new ListNode(carry);
}
return head.next;
}
private static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}