Add Two Sum

LeetCode 2

class Solution:
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        # 給個新LinkList去儲存新元素
        # tmp 變數是因為變換中須給指標指新位子
        root = tmp = ListNode(0)
        carry = 0 
        
        while l1 or l2 or carry:
            # v1 = v2 = 0 是預防1. 其中一個List 空了 2. 最後只有carry時的處理
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            
            carry, reminder = divmod(carry + v1 + v2, 10) 
            node = ListNode(reminder)
            tmp.next = node
            tmp = node
        
        return root.next

Last updated