[LeetCode] 2. 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.

Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

 

這道並不是什么難題,算法很簡單,鏈表的數據類型也不難,就是建立一個新鏈表,然后把輸入的兩個鏈表從頭往后擼,每兩個相加,添加一個新節點到新鏈表后面。為了避免兩個輸入鏈表同時為空,我們建立一個 dummy 結點,將兩個結點相加生成的新結點按順序加到 dummy 結點之后,由於 dummy 結點本身不能變,所以用一個指針 cur 來指向新鏈表的最后一個結點。好,可以開始讓兩個鏈表相加了,這道題好就好在最低位在鏈表的開頭,所以可以在遍歷鏈表的同時按從低到高的順序直接相加。while 循環的條件兩個鏈表中只要有一個不為空行,由於鏈表可能為空,所以在取當前結點值的時候,先判斷一下,若為空則取0,否則取結點值。然后把兩個結點值相加,同時還要加上進位 carry。然后更新 carry,直接 sum/10 即可,然后以 sum%10 為值建立一個新結點,連到 cur 后面,然后 cur 移動到下一個結點。之后再更新兩個結點,若存在,則指向下一個位置。while 循環退出之后,最高位的進位問題要最后特殊處理一下,若 carry 為1,則再建一個值為1的結點,代碼如下:

 

C++ 解法: 

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(-1), *cur = dummy;
        int carry = 0;
        while (l1 || l2) {
            int val1 = l1 ? l1->val : 0;
            int val2 = l2 ? l2->val : 0;
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            cur->next = new ListNode(sum % 10);
            cur = cur->next;
            if (l1) l1 = l1->next;
            if (l2) l2 = l2->next;
        }
        if (carry) cur->next = new ListNode(1);
        return dummy->next;
    }
};

 

Java 解法:

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int d1 = l1 == null ? 0 : l1.val;
            int d2 = l2 == null ? 0 : l2.val;
            int sum = d1 + d2 + carry;
            carry = sum >= 10 ? 1 : 0;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        if (carry == 1) cur.next = new ListNode(1);
        return dummy.next;
    }
}

 

在 CareerCup 上的這道題還有個 Follow Up,把鏈表存的數字方向變了,原來是表頭存最低位,現在是表頭存最高位,請參見我的另一篇博客 2.5 Add Two Numbers 兩個數字相加

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/2

 

類似題目:

Multiply Strings

Add Binary

Sum of Two Integers 

Add Strings 

Add Two Numbers II  

 

參考資料:

https://leetcode.com/problems/add-two-numbers/

https://leetcode.com/problems/add-two-numbers/discuss/997/c%2B%2B-Sharing-my-11-line-c%2B%2B-solution-can-someone-make-it-even-more-concise

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

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



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