原题链接:https://leetcode.com/problems/monotone-increasing-digits/description/
描述:
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].
Solution:
本题依然是数学问题,只需要找出需要调整的数即可,然后其后面的数全部赋9即可保证最大,分几种情况讨论,从位数低的开始考虑,需要找出的是最后一次从右向左出现递增的位置,然后中间需要加上数字重复的情况,如果数字重复刚好出现在递增的位置,那么也同样移动标记位,但如果没有移动过标记位,则将原数输出,具体代码如下所示:
#include <iostream>
#include <cmath>
using namespace std;
int monotoneIncreasingDigits(int N) {
int i = 0; // 记录需要调整的位置
int j = 0; // 位数
bool flag = 0; // 标记是否是转折点
int n = N;
int m1 = n % 10; // 末位数
n = n / 10;
while (n) {
j++;
int m2 = n % 10;// 倒数第二个数
if (m1 < m2) {
flag = 1;
i = j;
} else {
if (flag && m1 == m2) i = j;
else flag = 0;
}
m1 = m2;
n /= 10;
}
return i == 0 ? N : ((N / int(pow(10, i)) - 1) * pow(10, i)
+ int(pow(10, i)) - 1);
}
int main() {
int N;
while (cin >> N) {
cout << monotoneIncreasingDigits(N) << endl;
}
system("pause");
return 0;
}