Monotone Increasing Digits
A.题意
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: 9Example 2:
Input: N = 1234
Output: 1234Example 3:
Input: N = 332
Output: 299Note:N is an integer in the range [0, 10^9].
这道题题意大致是让你从给定的数字范围内选一个最大的递增数字
B.思路
这道题应该就是贪心算法了,从后向前扫描这个数字遇到后面比前面小的前面数字减一并且后面全部变成9,要保证这是数字中最前面的满足上面说的那个条件的位置。
C.代码实现
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string str = to_string(N);
int n = str.size(), j = n;
for (int i = n - 1; i > 0; i--)
{
if (str[i] >= str[i - 1])
{
continue;
}
else {
str[i - 1]--;
j = i;
}
}
for (int i = j;i < n;i++)
{
str[i] = '9';
}
return stoi(str);
}
};