Add Two Numbers[LeetCode/Python3/Medium]

 

題目

給你兩個非空的鏈表,分別表示兩個非負整數。數字以相反的順序存儲,每個節點包含一個數字。將兩個數字相加並以鏈表形式返回其和。

你可以假設除了數字0本身,這兩個數字都不會以0開頭。

例子1:

https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg

輸入: l1 = [2,4,3], l2 = [5,6,4]
輸出: [7,0,8]
解釋: 342 + 465 = 807.

例子2:

輸入: l1 = [0], l2 = [0]
輸出: [0]

例子3:

輸入: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
輸出: [8,9,9,9,0,0,0,1]

限制:

  • 鏈表中節點數目在範圍 [1, 100] 中。
  • 0 <= Node.val <= 9
  • 題目保證鏈表表示的數字不含前導零。

我的答案

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        Output_Node=ListNode()
        Output_currentNode=Output_Node
        value=0

        while l1 and l2 :
            
            value += l1.val+l2.val

            Output_currentNode.val=value%10
            value=value//10

            l1=l1.next
            l2=l2.next
            if l1 and l2:
                Output_currentNode.next=ListNode()
                Output_currentNode=Output_currentNode.next
            
        
        if l1 :
            Output_currentNode.next=ListNode()
            Output_currentNode=Output_currentNode.next
            while l1:
                value+=l1.val

                Output_currentNode.val=value%10
                value=value//10
                
                l1=l1.next
                if l1:
                    Output_currentNode.next=ListNode()
                    Output_currentNode=Output_currentNode.next
        elif l2 :
            Output_currentNode.next=ListNode()
            Output_currentNode=Output_currentNode.next
            while l2:
                value+=l2.val
                
                Output_currentNode.val=value%10
                value=value//10
                
                l2=l2.next
                if l2:
                    Output_currentNode.next=ListNode()
                    Output_currentNode=Output_currentNode.next

        if value >0:
            Output_currentNode.next=ListNode()
            Output_currentNode=Output_currentNode.next
            Output_currentNode.val=value

        return Output_Node



留言

這個網誌中的熱門文章

[理財/記帳]google表單結合iphone捷徑 自製記帳app

[理財/記帳]利用google表單記帳雲端化 - 免費模板下載@ Mimi's learning notes

[理財/記帳]懶人記帳-現金流+信用卡管理記帳法-不用天天記帳