
文章目录
16.单调递增的数字
16.1题目
当且仅当每个相邻位数上的数字 x
和 y
满足 x <= y
时,我们称这个整数是单调递增的。
给定一个整数 n
,返回 小于或等于 n
的最大数字,且数字呈 单调递增 。
-
示例一:
输入: n = 10
输出: 9 -
示例二:
输入: n = 1234
输出: 1234
16.2解法:贪心
16.2.1贪心思路

16.2.2代码实现
java
public int monotoneIncreasingDigits(int n) {
String s=String.valueOf(n);
char[] ch=s.toCharArray();
int len=ch.length;
int start=len; //从哪位开始变成9
for(int i=len-1;i>0;i--){
if(ch[i-1]>ch[i]){
//前一位比该位大
ch[i-1]--;
start=i;
}
}
for(int i=start;i<len;i++){
ch[i]='9';
}
return Integer.parseInt(String.valueOf(ch));
}
