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
题目给出一个数字N,让输出一个<=N小,而且要逐位升序(包括相等)的数字
图中example3,如果输出=N的数字,因为N中后面两位是降序的,所以要想升序,只能最大299
思路:
N如果是个位数,直接输出N就可以了
N的位数>=2时,类似31.Next Permutation的思路
31题因为数字是固定的,只能调换顺序,所以找到降序的位置,和降序后面的仅比它大的数字交换,然后降序后面的部分升序排列
此题因为不需要固定数字,同样也是找到降序的地方,降序后面的部分直接全部换成最大的9
**为了方便数字逐位操作,把int型数字转化成char数组
注意降序后面换成9的部分
比如332,检测到降序的index是i=2
这时候应该把index前面的一位 j 数字 -1. 变成322
因为输出的结果中不能有降序的数字,所以遇到降序仍然往前 -1
这时候j指向2,j的前面一位3仍然>2
再把j前面一位-1, 变成222
这时候从现在的j+1开始到后面全部变成9,即299
int j = i;
while (j >= 1 && num[j] < num[j - 1]) {
//1ms
public int monotoneIncreasingDigits(int N) {
if (N < 10) {
return N;
}
char[] num = String.valueOf(N).toCharArray();
int index = num.length;
for (int i = 1; i < num.length; i++) {
if (num[i - 1] > num[i]) {
int j = i;
while (j >= 1 && num[j] < num[j - 1]) {
num[--j] --;
}
index = j + 1;
break;
}
}
for (int j = index; j < num.length; j ++) {
num[j] = '9';
}
return Integer.parseInt(String.valueOf(num));
}