以下代码不适用于以下输入: [2,4,3] [5,6,4] 输出: [7,8] 预期: [7,0,8]
为什么我没有0?任何人都可以帮助我。
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode AddTwoNumbers(ListNode l1, ListNode l2) {
return AddTwoNumbersHelper(l1, l2, 0);
}
private ListNode AddTwoNumbersHelper(ListNode l1, ListNode l2, int carry) {
if (l1 == null && l2 == null)
return null;
int temp = 0;
if (l1 != null)
temp += l1.val;
if (l2 != null)
temp += l2.val;
ListNode result = new ListNode(temp % 10);
carry = temp / 10;
l1 = l1.next;
l2 = l2.next;
int sum = 0;
while(l1 != null || l2 != null) {
sum = carry;
if (l1 != null)
sum += l1.val;
if (l2 != null)
sum += l2.val;
carry = sum == 0 ? 0 : sum / 10;
sum = sum % 10;
result.next = new ListNode(sum);
if(l1 != null)
l1 = l1.next;
if(l2 != null)
l2 = l2.next;
}
if (carry > 0)
result.next = new ListNode(carry);
return result;
}
}
答案 0 :(得分:0)
代码存在一些缺陷:
这是经过稍微修改的解决方案,可以解决上述问题:
private ListNode AddTwoNumbersHelper(ListNode l1, ListNode l2) {
ListNode result = null;
ListNode tail = null;
int carry = 0;
while ((l1 != null) || (l2 != null) || (carry != 0)) {
int sum = carry;
if (l1 != null) {
sum += l1.val;
l1 = l1.next;
}
if (l2 != null) {
sum += l2.val;
l2 = l2.next;
}
carry = sum/10;
sum %= 10;
if (result == null) { // first time
result = new ListNode(sum);
tail = result;
} else {
tail.next = new ListNode(sum);
tail = tail.next;
}
}
return result;
}