Skip to content

Latest commit

 

History

History
56 lines (44 loc) · 1.07 KB

2.md

File metadata and controls

56 lines (44 loc) · 1.07 KB

Add Two Numbers

Description

link


Solution

See Code


Code

Complexity T : O(n) M : O(n)

# Definition for singly-linked list.
# class ListNode:
#     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
        """
        node = head = ListNode
        carry = 0
        while l1 and l2:
            s = l1.val + l2.val + carry
            carry = s // 10
            num = s % 10
            node.next = ListNode(num)
            node = node.next
            l1 = l1.next
            l2 = l2.next
        
        left = l1 if l1 else l2
        while left:
            s = left.val + carry
            carry = s // 10
            num = s % 10
            node.next = ListNode(num)
            node = node.next
            left = left.next
        
        if carry:
            node.next = ListNode(carry)
        return head.next