Sum—LeetCode-445 Add Two Numbers II

来源:互联网 发布:php分页步骤 编辑:程序博客网 时间:2024/05/17 07:55

题目描述:

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:

What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

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

Output: 7 -> 8 -> 0 -> 7


思想:先不带进位相加,再加上进位就行(加进位要注意移动一位),时间复杂度O(n^2)

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {        int len1 = getLen(l1);        int len2 = getLen(l2);        ListNode listNode1 = null, listNode2 = null, cNode = null, resNode = null;        if(len1 >= len2){            listNode1 = l1;            listNode2 = l2;        } else {            listNode1 = l2;            listNode2 = l1;        }        int maxLen = Math.max(len1, len2);        int minLen = Math.min(len1, len2);        int diff = maxLen - minLen, i = 0, j = 0;        // 实现不进位的加法        int first = 0;        cNode = new ListNode(0);        resNode = new ListNode(0);        ListNode cHead = cNode, resHead = resNode;        while(first < diff) {            ListNode tempNode1 = new ListNode(0);            cNode.next = tempNode1;            cNode = tempNode1;            ListNode tempNode2 = new ListNode(listNode1.val);            resNode.next = tempNode2;            resNode = tempNode2;            listNode1 = listNode1.next;            ++first;        }        while(first < maxLen) {            int sum = listNode1.val + listNode2.val;            ListNode tempNode1 = new ListNode(sum / 10);            cNode.next = tempNode1;            cNode = tempNode1;            ListNode tempNode2 = new ListNode(sum % 10);            resNode.next = tempNode2;            resNode = tempNode2;            listNode1 = listNode1.next;            listNode2 = listNode2.next;            ++first;        }        // 加上进位,每次相加,需要左移一下进位        int k = 0;        ListNode ccNode = cHead.next;        while (k < maxLen){            ListNode rresNode = resHead;            ListNode curCCNode = ccNode; // 保存当前进位点            while(null != ccNode){                int tempSum = rresNode.val + ccNode.val;                rresNode.val = tempSum % 10;                ccNode.val = tempSum / 10;                ccNode = ccNode.next;                rresNode = rresNode.next;            }            ccNode = curCCNode.next;            ++k;        }        if(resHead.val == 0)            return resHead.next;        return resHead;    }    private int getLen(ListNode l) {        int len = 0;        while(null != l) {            ++len;            l = l.next;        }        return len;    }



原创粉丝点击