[LeetCode-Java]2. Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

解:由于int大小限制,不可转化为int相加处理。对应位相加的过程中需注意末尾进位情况。

public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode result = l1;

        boolean flag = false;

        while(true){

            //对应位相加  考虑前一位的进位flag
            l1.val = l1.val + l2.val + (flag?1:0);

            //根据相加的结果  设置进位标志
            if (l1.val >= 10){
                l1.val = l1.val - 10;
                flag = true;
            }else {
                flag = false;
            }

            if (l1.next == null || l2.next == null)  break;

            l1 = l1.next;
            l2 = l2.next;
        }
        //l2长度比较长,作相应处理
        if (l1.next == null && l2.next != null){
            l2 = l2.next;
            l1.next = l2;

           dealWithEnd(l2,flag);

        }

        //l1的长度比较长
        if (l2.next == null && l1.next != null){
            l1 = l1.next;
            dealWithEnd(l1,flag);


        }
        //两者长度相同,需根据进位情况增加一个最高位
        if (l1.next == null && l2.next == null){
            if (flag) {
                ListNode end = new ListNode(1);
                l1.next = end;
            }
        }

        return result;

    }

    //对附带进位信息的链表进行处理
    static void dealWithEnd(ListNode listNode,Boolean flag){
        while (true){
            listNode.val  += (flag?1:0);

            if (listNode.val >= 10){
                listNode.val = listNode.val - 10;
                flag = true;
            }else {
                flag = false;
                break;
            }

            if (listNode.next == null){
                if (flag) {
                    ListNode end = new ListNode(1);
                    listNode.next = end;
                }
                break;
            }

            listNode = listNode.next;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值