题目: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].
题解:
我们只需要找到最左边出现逆序的数字所在位即可,将这个数字-1,这个数字后面的位全变为9
注意一种比较极端的情况,就是当14444687
python code:
def monotoneIncreasingDigits(self, N):
“”"
:type N: int
:rtype: int
“”"
s=list(str(N))
maker=len(s)
for i in xrange(maker-1,0,-1):
if s[i]<s[i-1]:
maker,s[i-1]=i,str(int(s[i-1])-1)
s[maker:]=[‘9’]*(len(s)-maker)
return int(’’.join(s))
c++ code:
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string s=to_string(N);
int maker=s.size();
for(int i=s.size()-1;i>0;i–)
{
if(s[i]<s[i-1])
{
maker=i;
s[i-1]=s[i-1]-1;
}
}
for(int i=maker;i<s.size();i++) s[i]=‘9’;
return stoi(s);
}
};