1 题目
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]
.
2 尝试解
2.1 分析
给定一个正整数M,返回一个正整数N,N为不大于M且数字非严格递增的最大正整数。
由于要求不超过M,且数字非严格递增,则高位变动得越少越好。Di表示M的第i位数,且Di满足下列条件的最小位上的数:Di>Di+1。由于要求不超过M,则不能直接将Di+1增加,只能将Di减少,此时Di以后的所有数位如何变动都不会超过M,不如令Di以后的所有位数都调整为9。则Di-1以后的位数都满足非严格递增,接着先向前遍历即可。
2.2 代码
class Solution {
public:
int monotoneIncreasingDigits(int N) {
int last = 9, cur = 0;
int result = 0;
for(int i = 1; N > 0; i*=10){
cur = N % 10;
if(cur > last){
cur--;
result = cur*i + i - 1;
}
else{
result = cur*i + result;
}
last = cur;
N= N / 10;
}
return result;
}
};
3 标准解
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string n_str = to_string(N);
int marker = n_str.size();
for(int i = n_str.size()-1; i > 0; i --) {
if(n_str[i] < n_str[i-1]) {
marker = i;
n_str[i-1] = n_str[i-1]-1;
}
}
for(int i = marker; i < n_str.size(); i ++) n_str[i] = '9';
return stoi(n_str);
}
};