Simple Python O(n) Solution without converting to a number


  • 2
    S

    The idea here is to start from the right side. As soon as we find a number that isn't 9 we can add 1 to it and return. If the number is 9, we change it to 0 and continue until we find a number that is not 9 to carry the 1 to. If we reach the end of array with all 9's we then insert the 1 in front of array.

     def plusOne(self, digits):
        for i in range(len(digits)-1, -1, -1):
            digits[i] = digits[i] + 1 if digits[i] < 9 else 0
            if digits[i]: 
                return digits
        digits.insert(0, 1)
        return digits

Log in to reply
 

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