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))