【leedcode】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 up = 0;
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode newList = new ListNode(-1);
        ListNode newNode, rootList = newList;
        while (l1 != null && l2 != null) {
            newNode = new ListNode(l1.val + l2.val + up);
            up = newNode.val /10;
            newNode.val = mod(newNode.val,10, up);
            newList.next = newNode;
            newList = newList.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        newList = loopList(l1, newList);
        newList = loopList(l2, newList);
        if (up > 0) {
            newList.next = new ListNode(up);
        }
        return rootList.next;
    }
    
    ListNode loopList(ListNode loopList, ListNode newList) {
        ListNode newNode;
        while (loopList != null) {
            newNode = new ListNode(loopList.val + up);
            up = newNode.val /10;
            newNode.val = mod(newNode.val, 10, up);
            newList.next = newNode;
            newList = newList.next;
            loopList = loopList.next;
        }
        return newList;
    }
    static int mod(int x, int y, int v) {
         return x - y * v;
    }

码出来的代码不不如答案,哎,超级简洁:

ListNode dummyHead = new ListNode(0);
    ListNode p = l1, q = l2, curr = dummyHead;
    int carry = 0;
    while (p != null || q != null) {
        int x = (p != null) ? p.val : 0;
        int y = (q != null) ? q.val : 0;
        int sum = carry + x + y;
        carry = sum / 10;
        curr.next = new ListNode(mod(sum , 10 , carry));
        curr = curr.next;
        if (p != null) p = p.next;
        if (q != null) q = q.next;
    }
    if (carry > 0) {
        curr.next = new ListNode(carry);
    }
    return dummyHead.next;

 

posted @ 2016-10-08 13:37  明将军  Views(193)  Comments(0Edit  收藏  举报
恨怨悲苦憎怒嗔、仁爱慈孝耻义廉。是故恨人所以得仁,无爱者必不怨,不慈者必无悲,孝而有苦,憎后耻来,义自怒生,廉人心嗔。夹天地七大苦,破人情七大碍,遂舍善恶之心,得称剑神。