[Leetcode][2][Add Two Numbers][Medium]

題目描述:

給定兩個鏈表,輸出兩個鏈表的和,具體形式如下:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

解題思路:

首先分別計算出每個鏈表的數(shù)字(342 and 465),然后在進行相加,把相加后的每一位存放進新的鏈表中。最后處理一下最高進位。python 代碼如下:

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        rest = ListNode(0)
        ans = rest
        
        suml = 0
        i = 1
        while l1 != None:
            suml += l1.val * i
            l1 = l1.next
            i *= 10
        
        i = 1
        while l2 != None:
            suml += l2.val * i
            l2 = l2.next
            i *= 10
            
        while suml != 0:
            ans.val = suml % 10
            suml /= 10
            if suml != 0:
                ans.next = ListNode(0)
                ans = ans.next
            
        return rest
?著作權(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)容