2.Add Two Numbers

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

翻譯
有兩個(gè)代表兩組非負(fù)數(shù)字的鏈表。兩個(gè)鏈表按照逆序排序,并且每一個(gè)節(jié)點(diǎn)包含一位數(shù)字。把兩組數(shù)加起來,并且返回一個(gè)鏈表。

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

審題
1.鏈表
2.一位數(shù)字
3.返回鏈表
4.根據(jù)例子知道,
Output:7->0->8
其中
7=3+4;
0=4+6;
8=2+5+1(進(jìn)位);

隱藏問題
鏈表可能很長很長。。。所以不能總是遍歷
兩個(gè)鏈表可能不一樣的長度,即有可能有些位不用做加法

我漏掉分析一個(gè),當(dāng)長度一樣的兩個(gè)鏈表,最后一位相加進(jìn)位了,我們需要把進(jìn)位補(bǔ)到鏈表最后。。。

Input: (5) + (5)
Output: 0 -> 1
Mine: 0

解決方案

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode result = new ListNode(0);
    int carry = 0;
    ListNode pointer = result;
    while (l1 != null || l2 != null) {
        //兩個(gè)有一個(gè)沒到頭,就繼續(xù)
        if (l1 != null) {
            carry += l1.val;
            l1 = l1.next;
        }
        
        if (l2 != null) {
            carry += l2.val;
            l2 = l2.next;
        }
        
        pointer.next = new ListNode(carry%10);
        carry /=10;
        pointer = pointer.next;
        
    }
    
    if (carry > 0) {//記得處理最后的進(jìn)位。。。
        pointer.next = new ListNode(carry);
    }
    
    return result.next;
}

https://leetcode.com/submissions/detail/25494001/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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