Python solution with detailed explanation


  • 0
    G

    Solution

    Plus One https://leetcode.com/problems/plus-one/

    Algorithm

    • Use a deque to store the result. Start from the end of the input and maintain the value of the new carry.
    from collections import deque
    class Solution(object):
        def plusOne(self, digits):
            """
            :type digits: List[int]
            :rtype: List[int]
            """
            result, carry = deque(), 1
            for i in range(len(digits)-1,-1,-1):
                r, carry = (digits[i]+carry)%10, (digits[i]+carry)//10
                result.appendleft(r)
            if carry == 1:
                result.appendleft(1)
            return [x for x in result]
    

Log in to reply
 

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