[Leetcode]Add Two Numbers鏈表數相加

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

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

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

遞歸寫法

複雜度

時間O(n) 空間(n) 遞歸棧空間

思路

是用java編寫,本題的思路很簡單,按照小學數學中學習的加法原理從末尾到首位,對每一位對齊相加即可。技巧在於如何處理不同長度的數字,以及進位和最高位的判斷。這裏對於不同長度的數字,我們通過將較短的數字補0來保證每一位都能相加。遞歸寫法的思路比較直接,即判斷該輪遞歸中兩個ListNode是否爲null。

  • 全部爲null時,返回進位值內容
  • 有一個爲null時,返回不爲null的那個ListNode和進位相加的值
  • 都不爲null時,返回 兩個ListNode和進位相加的值

    public class Solution {
            public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
                return helper(l1,l2,0);
    }
    
    public ListNode helper(ListNode l1, ListNode l2, int carry){
        if(l1==null && l2==null){
            return carry == 0? null : new ListNode(carry);
        }
        if(l1==null && l2!=null){
            l1 = new ListNode(0);
        }
        if(l2==null && l1!=null){
            l2 = new ListNode(0);
        }
        int sum = l1.val + l2.val + carry;
        ListNode curr = new ListNode(sum % 10);
        curr.next = helper(l1.next, l2.next, sum / 10);
        return curr;
    }
    }
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章