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]
.
import java.util.ArrayList;
import java.util.List;
class Solution {
public int monotoneIncreasingDigits(int N) {
// 提取出整数N各位上的数字
List<Integer> digits = new ArrayList<>();
while (N >= 10) {
digits.add(0,N%10);
N /= 10;
}
digits.add(0, N);
// 检查当前各位数字是否递增
while (!checkValid(digits)) {
// 如遇到非递增的情况,调整
transform(digits);
}
// 若首位数字为0,删除
while (digits.get(0) == 0) {
digits.remove(0);
}
// 将各位上的数字组装成一个整数
String strResult = "";
for (int dgt :digits) {
strResult += dgt;
}
return Integer.valueOf(strResult);
}
private void transform(List<Integer> digits) {
int pre = digits.get(0);
// 从首向尾遍历,找出首次出现非递增的一对数
for (int i = 1; i < digits.size(); i++) {
if (digits.get(i) < pre) {
digits.set(i-1, pre-1);
for (int j = i; j < digits.size(); j++) {
digits.set(j, 9);
}
break;
}
pre = digits.get(i);
}
}
// 检查是否递增
private boolean checkValid(List<Integer> digits) {
int pre = -1;
for (int d : digits) {
if (pre > d) {
return false;
}
pre = d;
}
return true;
}
}