LeetCode解题 2:Add Two Numbers
Problem 2: Add Two Numbers [Medium]
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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
来源:LeetCode
Solution (Java)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode tail = null;
for(; l1 != null && l2 != null; l1 = l1.next, l2 = l2.next){
ListNode l3 = new ListNode(l1.val + l2.val);
if(head == null){
head = l3;
}
else{
if(tail.val >= 10){
tail.val -= 10;
l3.val += 1;
}
tail.next = l3;
}
tail = l3;
}
while(l1 != null){
ListNode l3 = new ListNode(l1.val);
if(tail.val >= 10){
tail.val -= 10;
l3.val += 1;
}
tail.next = l3;
tail = l3;
l1 = l1.next;
}
while(l2 != null){
ListNode l3 = new ListNode(l2.val);
if(tail.val >= 10){
tail.val -= 10;
l3.val += 1;
}
tail.next = l3;
tail = l3;
l2 = l2.next;
}
if(l1 == null && l2 == null && tail.val >= 10){
ListNode l3 = new ListNode(1);
tail.val -= 10;
tail.next = l3;
}
return head;
}
}
修改过程
- while循环体内忘记写
tail.next = l3
,导致输入[1,8] [0],输出错误答案为[1]。 - 末尾进位的if判断没有写在最后,没有考虑两数长度不一致并且最后需要进位的情况,导致输入[1] [9,9],输出错误答案为[0,10]。