【LeetCode】2. Add Two Numbers 解题报告


转载请注明出处:http://blog.csdn.net/crazy1235/article/details/52914703


Subject

出处:https://leetcode.com/problems/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


Explain

有两个链表,它们表示逆序的两个非负数。计算出两个数的和之后,同样逆序输出作为一个链表。

需要注意一点:有进位


Solution

solution 1

便利两个链表,以此相加,把进位的数字计入下一组相加的数字中。

需要注意一种情况,比如{5} , {5}两个列表,输出的结果应该是{0, 1}

/**
     * 57ms 
* 将个数较少的列表后面补上0 * * @param l1 * @param l2 * @return */
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if (l1 == null || l2 == null) { return null; } ListNode temp = new ListNode(0); ListNode result = temp; int value1 = 0; int value2 = 0; while (l1 != null && l2 != null) { value2 = (l1.val + l2.val + value1) % 10; value1 = (l1.val + l2.val + value1) / 10; temp.next = new ListNode(value2); l1 = l1.next; l2 = l2.next; temp = temp.next; if (l1 == null && l2 == null) { break; } if (l1 == null) { l1 = new ListNode(0); } if (l2 == null) { l2 = new ListNode(0); } } if (value1 != 0) { temp.next = new ListNode(value1); } return result.next; }

solution 2

递归方式。

/**
     * 递归方式 -- 56ms
     * 
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        int value = l1.val + l2.val;
        ListNode result = new ListNode(value % 10);
        result.next = addTwoNumbers2(l1.next, l2.next);
        if (value >= 10) {
            result.next = addTwoNumbers2(new ListNode(value / 10), result.next);
        }
        return result;
    }

solution 3

摘自『九章算法』的答案。

将过程分为三种情况。现将两个链表等长度对应的数字之和计算出来,然后两个链表有一个为空了。此时分两种情况(类似情况)。如果l1不为空,则将l1链表的值与“进位”相加再取余做为下一个结果元素的值。

/**
     * 九章算法答案 
* http://www.jiuzhang.com/solutions/add-two-numbers/ * * @param l1 * @param l2 * @return */
public ListNode addTwoNumbers3(ListNode l1, ListNode l2) { if (l1 == null && l2 == null) { return null; } ListNode head = new ListNode(0); ListNode point = head; int carry = 0; while (l1 != null && l2 != null) { int sum = carry + l1.val + l2.val; point.next = new ListNode(sum % 10); carry = sum / 10; l1 = l1.next; l2 = l2.next; point = point.next; } while (l1 != null) { int sum = carry + l1.val; point.next = new ListNode(sum % 10); carry = sum / 10; l1 = l1.next; point = point.next; } while (l2 != null) { int sum = carry + l2.val; point.next = new ListNode(sum % 10); carry = sum / 10; l2 = l2.next; point = point.next; } if (carry != 0) { point.next = new ListNode(carry); } return head.next; }

bingo~~

【LeetCode】2. Add Two Numbers 解题报告_第1张图片

你可能感兴趣的:(Java开发,算法学习,LeetCode解题报告,Java,篇)