Share my beats 60% Python solution using deque


  • 0
    I

    I used the the same concept as adding two numbers represented by linked lists. Working from the right most digit and add carry (1) all the way to the left. And for a quicker "append left" operation, I used deque. Remember to convert the deque object to a list before returning the result

        def plusOne(self, digits):
            """
            :type digits: List[int]
            :rtype: List[int]
            """
            carry = 0
            queue = collections.deque(digits)
            index = len(queue) - 1
            carry = (queue[index] + 1) // 10
            queue[index] = (queue[index] + 1) % 10
            index -= 1
            while carry:
                if index < 0:
                    queue.appendleft(carry)
                    return list(queue)
                carry = (queue[index] + 1) // 10
                queue[index] = (queue[index] + 1) % 10
                index -= 1
            return list(queue)
    

Log in to reply
 

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