Beat 95% speed python solution


  • 0
    B
    class ListNode(object):
        def __init__(self, x):
            self.val = x
            self.next = None
    
    class Solution(object):
        def addTwoNumbers(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if l1 is None or l2 is None:
                return None
            
            dummy = l1
            carry = 0
            while(l1 is not None and l2 is not None):
                l1.val += (l2.val + carry)
                if l1.val >= 10:
                    carry = 1
                    l1.val -= 10
                else:
                    carry = 0
                pre_l1 = l1
                l1 = l1.next
                l2 = l2.next
                
            if l1 is None:
                pre_l1.next = l2
                
            l1 = pre_l1
                
            while(carry != 0):
                if l1.next is None:
                    l1.next = ListNode(0)
                l1 = l1.next
                l1.val += carry
                if l1.val >= 10:
                    carry = 1
                    l1.val -= 10
                else:
                    carry = 0
                    
            return dummy
    

  • 0
    B

    O(1) space complexity


  • 0
    S
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.