Python simple solution using recursion


  • 8
    W
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if len(digits) == 0:
            digits = [1]
        elif digits[-1] == 9:
            digits = self.plusOne(digits[:-1])
            digits.extend([0])
        else:
            digits[-1] += 1
        return digits

  • 2
    S

    Here is what I did.

    def plusOne(self, digits):
        digits = digits or [0]
        last = digits.pop()
        
        if last == 9:
            return self.plusOne(digits) + [0]
        else:
            return digits + [last + 1]
    

  • 0
    K

    @woostundy The edge case handling an empty array of digits is actually unnecessary as it is given that digits contains at least one number.

    I also opted for a recursive solution which I find more intuitive, since it corresponds to my visualization of changing the 9 to a 0 in place and appending a 1 to the front if necessary:

    class Solution:
        def plusOne(self, digits):
            if digits[-1] < 9:
                digits[-1] += 1
            elif digits[-1] == 9:
                digits[-1] = 0
                if len(digits) == 1:
                    digits.insert(0, 1)
                else:
                    digits[:-1] = self.plusOne(digits[:-1])
            return digits
    

Log in to reply
 

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