leetcode2 addTwoNumbers

第一天: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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值