LeetCode Everyday:堅持價值投資,做時間的朋友!!!
題目:
給出兩個 非空 的鏈表用來表示兩個非負的整數。其中,它們各自的位數是按照 逆序 的方式存儲的,並且它們的每個節點只能存儲 一位 數字。
如果,我們將這兩個數相加起來,則會返回一個新的鏈表來表示它們的和。您可以假設除了數字 0 之外,這兩個數都不會以 0 開頭。
示例:
輸入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
輸出:7 -> 0 -> 8
原因:342 + 465 = 807
代碼
方法一: 設置進位,需要注意的就是等長鏈表相加最後如果有進位,需要增加一個節點存進位就可以了
執行用時 :80 ms, 在所有 Python3 提交中擊敗了44.43%的用戶
內存消耗 :13.7 MB, 在所有 Python3 提交中擊敗了5.13%的用戶
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
curr = head = ListNode(0)
while l1 or l2:
val = carry
if l1:
val += l1.val
l1 = l1.next
if l2:
val += l2.val
l2 = l2.next
curr.next = ListNode(val % 10)
curr = curr.next
carry = val // 10
if carry > 0:
curr.next = ListNode(carry)
return head.next
"""
For Example: input: l1: 2->4->3 l2: 5->6->4
output: 7->0->8
"""
l1 = ListNode(2)
l1.next = ListNode(4)
l1.next.next = ListNode(3)
l2 = ListNode(5)
l2.next = ListNode(6)
l2.next.next = ListNode(4)
solution = Solution()
result = solution.addTwoNumbers(l1, l2)
print('輸出爲:%d->%d->%d' % (result.val, result.next.val, result.next.next.val)) # 7->0->8
圖解:
引用的圖片展示的是方法一的動態過程,可以幫助分析,很不錯
參考
- https://github.com/MisterBooo/LeetCodeAnimation