738 Monotone Increasing Digits
Given a non-negative integerN, find the largest number that is less than or equal toNwith monotone increasing digits.
(Recall that an integer hasmonotone increasing digitsif and only if each pair of adjacent digitsxandysatisfyx <= y.)
Example 1:
Input:
N = 10
Output:
9
Example 2:
Input:
N = 1234
Output:
1234
Example 3:
Input:
N = 332
Output:
299
Note:Nis an integer in the range[0, 10^9].
Solution)
class Solution {
public int monotoneIncreasingDigits(int N) {
char[] x = String.valueOf(N).toCharArray();
int mark = x.length;
for(int i = x.length-1;i>0;i--){
if(x[i]<x[i-1]){
mark = i-1;
x[i-1]--;
}
}
for(int i = mark+1;i<x.length;i++){
x[i] = '9';
}
return Integer.parseInt(new String(x));
}
}