7 Line Python solution using string with simple explanation


  • 0
    I

    Idea:
    Find the first digit which is smaller than previous, turn the digit and the ones afterwards into 0, then reduce 1.
    Note that if the "previous" digit is repeated, only the first of those repeated digit should be kept and others should also be turned into 0.
    Use string to simplify coding.

        def monotoneIncreasingDigits(self, N):
            Nstr, pIdx = str(N), 0
            for i in range(1,len(Nstr)):
                if Nstr[i] > Nstr[i-1]:
                    pIdx = i
                elif Nstr[i] < Nstr[i-1]:
                    return int(Nstr[:pIdx+1] + '0'*(len(Nstr)-pIdx-1))-1
            return N
    

Log in to reply
 

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