1. 程式人生 > 其它 >Leetcode Add Two Numbers java_解題報告

Leetcode Add Two Numbers java_解題報告

1.問題描述

給你兩個非空的連結串列,表示兩個非負的整數。它們每位數字都是按照逆序方式儲存的,並且每個節點只能儲存一位數字。
請你將兩個數相加,並以相同形式返回一個表示和的連結串列。
你可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。

2.測試用例

示例 1:
輸入:l1 = [2,4,3], l2 = [5,6,4]
輸出:[7,0,8]
解釋:342 + 465 = 807.

示例 2:
輸入:l1 = [0], l2 = [0]
輸出:[0]

示例 3:
輸入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出:[8,9,9,9,0,0,0,1]

3.補充說明

每個連結串列中的節點數在範圍 [1, 100] 內
0 <= Node.val <= 9
題目資料保證列表表示的數字不含前導零

4.解題報告

  1. 遞迴
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode currentNode = new ListNode();
            int next = 0;
            currentNode = assignListNode(l1, l2, currentNode, next);
            return currentNode;
        }
        
        public ListNode assignListNode(ListNode l1, ListNode l2, ListNode currentNode, int next) {
            if (l1 == null && l2 == null) {
                if (next > 0) {
                    currentNode.val = 1;
                } else {
                    currentNode = null;
                }
                return currentNode;
            }
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + next;
            currentNode.val = sum % 10;
            currentNode.next = new ListNode();
            currentNode.next = assignListNode(l1 == null ? null : l1.next, l2 == null ? null : l2.next, currentNode.next, sum / 10);
            return currentNode;
        }
    }
    
  2. 內迴圈
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        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(sum % 10);
            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;
    }