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
这题暴力解法就是一个个数check,超时。
贪心算法,构造需要的解去试。
key point就是,如果已知现有的部分是‘123’,下一个数字最大可以是多少了?比如5,那么就要保证1235…5 <= N。在这个要求下去找每一位可能的数字就行。
代码:
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string res = "";
string num = to_string(N);
for (int i = 0; i < num.size(); i++) {
int flag = false;
for (char c = '1'; c <= '9'; c++) {
string temp= res;
while (temp.size() < num.size()) temp += c;
if (temp > num) {
res += c - 1;
flag = true;
break;
}
}
if (flag == false) res += '9';
}
return stoi(res);
}
};