第一天:2. Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
我的答案:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null & l2 == null) {
return new ListNode();
}
if (l1 == null) return l2;
if (l2 == null) return l1;
int i1 = 0, i2 = 0;
int a1 = 1, a2 = 1;
while (l1 != null) {
i1 = i1 + l1.val * a1;
l1 = l1.next;
a1 *= 10;
}
while (l2 != null) {
i2 = i2 + l2.val * a2;
l2 = l2.next;
a2 *= 10;
}
/**
* 此时如果是大数,这超出int 范围,所以这种写法是错误的
* [9]
* [1,9,9,9,9,9,9,9,9,9]
*
* 结果是:
* 9
* 1410065399
* 1410065408
*
*/
System.out.println(i1);
System.out.println(i2);
int res = i1 + i2;
System.out.println(res);
int index = String.valueOf(res).length();
ListNode node = new ListNode();
ListNode pre = node;
while (index > 0) {
ListNode next = new ListNode();
int temp = res % 10;
res = res / 10;
node.val = temp;
index = index - 1;
// node.next = next;
// node = next;
if (index > 0) {
node.next = next;
node = next;
}
}
return pre;
}
}
正确答案:
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode curr = new ListNode(0);
ListNode p = l1, q = l2, pre = curr;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int res = carry + x + y;
carry = res / 10;
curr.next = new ListNode(res % 10);
curr = curr.next;
// 注意这里是 p!= null 而不是 p.next != null,否则会在最后一个节点一直循环
if(p!= null) p = p.next;
if(q!= null) q = q.next;
}
if (carry >0) {
curr.next = new ListNode(carry);
}
return pre.next;
}
}