题目
当且仅当每个相邻位数上的数字 x 和 y 满足 x <= y 时,我们称这个整数是单调递增的。
给定一个整数 n ,返回 小于或等于 n 的最大数字,且数字呈 单调递增 。
代码
class Solution {
public int monotoneIncreasingDigits(int n) {
String str = Integer.toString(n); //将数字转化为字符串
char[] chars = str.toCharArray();
int len = chars.length;
int flag = len; // 标记从哪一位统一改为9
//从后向前遍历
for(int i = len-1;i > 0; i--){
if(chars[i-1] > chars[i]){
chars[i-1]--;
flag = i;
}
}
for(int i = flag; i < len; i++){
chars[i] = '9';
}
return Integer.parseInt(new String(chars));
}
}