LeetCode 2. Add Two Numbers (兩數相加)


題目標簽:Linked List, Math

  題目給了我們兩個 Linked List, 各代表一個數字,不過順序的反的。讓我們把兩個數字相加。

  和普通的相加其實差不多,只不過變成了 Linked List, 還是要用到 / 和 %,具體看code。

 

Java Solution:

Runtime:  2ms, faster than 87% 

Memory Usage: 44MB, less than 85%

完成日期:07/05/2019

關鍵點:利用 / 取得 carry;利用 % 取得 余數

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        
        ListNode dummyHead = new ListNode(0);
        ListNode cursor1 = l1;
        ListNode cursor2 = l2;
        ListNode cursor3 = dummyHead;
        
        int carry = 0;
        
        while(cursor1 != null || cursor2 != null) // go through both list
        {
            // if node exists, get the value, elsewise, default 0
            int num1 = 0;
            int num2 = 0;
            
            if(cursor1 != null)
                num1 = cursor1.val;
            if(cursor2 != null)
                num2 = cursor2.val;
            
            
            int sum = num1 + num2 + carry;
            
            // update carry and sum
            carry = sum / 10;
            cursor3.next = new ListNode(sum % 10);
            cursor3 = cursor3.next;
            
            // move both list to next node
            if(cursor1 != null)
                cursor1 = cursor1.next;
            if(cursor2 != null)
                cursor2 = cursor2.next;
        }
        
        // at last, still need to check carry for last digit
        if(carry == 1)
            cursor3.next = new ListNode(1);
        
        return dummyHead.next;
    }
}

參考資料:N/A

LeetCode 題目列表 - LeetCode Questions List

題目來源:https://leetcode.com/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM