qq_46081891
2021-09-25 12:13
采纳率: 0%
浏览 23

leetcode的两数相加,java,为什么运行结果少一位数

这是我代码的显示结果
解答失败:
测试用例:[9,9,9,9,9,9,9]
[9,9,9,9]
测试结果:[8,9,9,9,0,0,0]
期望结果:[8,9,9,9,0,0,0,1]

这是具体代码:

class Solution {
    ListNode res = null, cur = null;
    int c = 0;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 != null || l2 != null) {
            int a = l1 != null ? l1.val + c : c;   //l1当前结点的值与进位的和
            int b = l2 != null ? l2.val : 0;       //l2当前结点的值
            int sum = (a + b) % 10;                //新链表当前节点的值
            c = (a + b) / 10;                      //进位值
            if (cur == null & res == null) {       
                res = cur = new ListNode(sum);
            } else {
                cur.next = new ListNode(sum);
                cur = cur.next;
            }
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
            if (l1 == null & l2 == null & c == 0) {
                return res;
            }
            addTwoNumbers(l1, l2);
        }
        return res;
    }
}


  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 码仔ROC 2021-09-28 09:53
    
    class Solution {
        ListNode res = null, cur = null;
        int c = 0;
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            if (l1 != null || l2 != null || c != 0) {
                int a = l1 != null ? l1.val + c : c;   //l1当前结点的值与进位的和
                int b = l2 != null ? l2.val : 0;       //l2当前结点的值
                int sum = (a + b) % 10;                //新链表当前节点的值
                c = (a + b) / 10;                      //进位值
                if (cur == null & res == null) {       
                    res = cur = new ListNode(sum);
                } else {
                    cur.next = new ListNode(sum);
                    cur = cur.next;
                }
                if (l1 != null) {
                    l1 = l1.next;
                }
                if (l2 != null) {
                    l2 = l2.next;
                }
                if (l1 == null & l2 == null & c == 0) {
                    return res;
                }
                addTwoNumbers(l1, l2);
            }
            return res;
        }
    }
     
    

    执行到最后一位L1和L2都是空,但c=1.
    修改一下判断:
    if (l1 != null || l2 != null || c != 0)

    下次提问把问题也复制上。还得自己去找问题

    打赏 评论

相关推荐 更多相似问题