Simple python solution with explanation

  • 0

    We only need to find the last digit which is less than 9, suppose the index is lastNotNine. After plus one, every digits after lastNotNine will be set to 0 and digits[lastNotNine] will increase by 1.
    The special situation need to be handled is that all input digits are 9, in such situation lastNotNine will be -1, then we insert a '1' to the front. Code is as following.

    class Solution(object):
        def plusOne(self, digits):
            :type digits: List[int]
            :rtype: List[int]
            lastNotNine = -1
            for i,d in enumerate(digits):
                if d < 9:
                    lastNotNine = i
            for i in range(lastNotNine+1,len(digits)):
                digits[i] = 0
            if lastNotNine != -1:
                digits[lastNotNine] += 1
            return digits

Log in to reply

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