738. Monotone Increasing Digits

88 篇文章 0 订阅
15 篇文章 0 订阅

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 = 10
Output: 9

 

Example 2:

Input: N = 1234
Output: 1234

 

Example 3:

Input: N = 332
Output: 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))

基本上怎么想的就怎么写,

1. 找到递增的位置

2. 递增前重复的最开头位置

3. 最开头减1(必然可以减1,不会为0),后面换成9

class Solution(object):
    def monotoneIncreasingDigits(self, N):
        """
        :type N: int
        :rtype: int
        """
        if N<10: return N
        s=str(N)
        i=1
        while i<len(s) and s[i]>=s[i-1]: i+=1
        if i==len(s): return N
        i-=1
        tmp=s[i]
        while i>=0 and s[i]==tmp: i-=1
        i+=1
        res=s[:i]+str(int(s[i])-1)+'9'*(len(s)-i-1)
        return int(res)
    
s=Solution()
print(s.monotoneIncreasingDigits(10))
print(s.monotoneIncreasingDigits(1234))
print(s.monotoneIncreasingDigits(332))
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值