Add Two Numbers

每日算法——letcode系列

標(biāo)簽: 算法 C++ LetCode


問題 Add Two Numbers

Difficulty: Medium

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        
    }
};

翻譯

兩鏈表對應(yīng)數(shù)之和

難度系數(shù):中等

給定兩個由正整數(shù)組成的鏈表,數(shù)在鏈表中是倒序存放的,并且每個節(jié)點上的數(shù)是一位整數(shù)。把這兩上鏈表上的數(shù)相加并返回一個鏈表

輸入: (2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出: 7 -> 0 -> 8

思路

題中為什么說倒序,因為如果(2 -> 4 -> 3)看成一個數(shù)應(yīng)該是243,如果跟(5 -> 6 -> 4)564相加應(yīng)該得807,但由于是倒序放的,應(yīng)該先從高位相加。

注意的是,題中沒有說兩個鏈表長度相同,我認(rèn)為應(yīng)該適應(yīng)長度不相同的時候,還有就是相加后的鏈表有可能多一位。

代碼

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        if (l1 == nullptr && l1 == nullptr){
            return nullptr;
        }
        
        ListNode* head = nullptr, **temp = &head;
        
        int carry = 0;
        while (l1 != nullptr || l2 != nullptr) {
            int a = getValAndMoveToNext(l1);
            int b = getValAndMoveToNext(l2);
            int newVal = (a + b + carry) % 10;
            carry = (a + b + carry) / 10;
            ListNode* node = new ListNode(newVal);
            *temp = node;
            temp = &node->next;
        }
        
        // 最后當(dāng)carrry大于0(為1)時,應(yīng)該進(jìn)一位
        if (carry > 0){
            ListNode* node = new ListNode(carry);
            *temp = node;
        }
        return head;
    }
    
private:
    int getValAndMoveToNext(ListNode* &l){
        if (l == nullptr){
            return  0;
        }
        
        int x = 0;
        x = l->val;
        l = l->next;
        return  x;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容