738. Monotone Increasing Digits

来源:互联网 发布:网易 魔兽对战平台 mac 编辑:程序博客网 时间:2024/05/21 14:51

Given a non-negative integer N, find the largest number that is less than or equal to N with monotone increasing digits.

(Recall that an integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.)

Example 1:

Input: N = 10Output: 9

Example 2:

Input: N = 1234Output: 1234

Example 3:

Input: N = 332Output: 299

Note: N is an integer in the range [0, 10^9].


从高位开始,check能不能保留下来此高位,如果可以,继续往后看能不能保存下一位
如果不可以,后面的全为9,前面所有高位减1
class Solution:    def monotoneIncreasingDigits(self, N):        """        :type N: int        :rtype: int        """        s = str(N)        l = len(s)        canKeep = True        for i in range(l):            if int(s[i]*(l-i))>int(s[i:]):                canKeep = False                break                if canKeep:  return N        if i==0:  return int(str(int(s[0]))+'0'*(l-1))-1        return int(str(int(s[:i+1]))+'0'*(l-i-1))-1    s = Solution()print(s.monotoneIncreasingDigits(120))print(s.monotoneIncreasingDigits(10))print(s.monotoneIncreasingDigits(1234))print(s.monotoneIncreasingDigits(332))


原创粉丝点击