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.)
Input: N = 10
Output: 9
Input: N = 1234
Output: 1234
Input: N = 332
Output: 299
class Solution {
public int monotoneIncreasingDigits(int N) {
// 思路:找出距离N最近的单调递增的数,将该数的各位均输出。只要找到第一个递减的数字(同时需要保证该index的数字减1后仍保持递增性),则该递减index后续的数均为999。
if(N==0){
return 0;
}
List<Integer> list=new ArrayList<>();
// 获取将目标数字的各位数字
helper(list,N);
List<Integer> res=new ArrayList<>();
int lastIndex=-1;
for(int i=list.size()-1;i>=0;i--){
if(i>0&&list.get(i)>list.get(i-1)){
// 递降
lastIndex=i;
break;
}else{
res.add(list.get(i));
}
}
if(lastIndex>0){
res.add(list.get(lastIndex)-1);
if(lastIndex==list.size()-1){
// 说明第一个就需要转换
for(int i=1;i<=list.size()-1;i++){
res.add(i,9);
}
}else{
// 对已经添加的数,保证递增性
dec(res);
for(int i=lastIndex-1;i>=0;i--){
res.add(9);
}
}
}
return assemble(res);
}
public void helper(List<Integer> list,int n){
if(n==0){
return;
}
while(n!=0){
int tmp=n%10;
list.add(tmp);
n/=10;
}
}
public void dec(List<Integer> list){
if(list==null||list.size()==0){
return ;
}
int i=list.size()-1;
while(i>0&&list.get(i)<list.get(i-1)){
list.set(i,9);
list.set(i-1,list.get(i-1)-1);
i--;
}
}
public int assemble(List<Integer> list){
if(list==null||list.size()==0){
return 0;
}
int totalCount=0;
for(int i=0;i<list.size();i++){
totalCount=totalCount*10+list.get(i);
}
return totalCount;
}
}
class Solution {
public int monotoneIncreasingDigits(int N) {
// 思路:如果出现递减的数,则该index之后的数据均为9,该index的数字-1,一直往前保持递增序列
int res=N%10;
int lsd=res,pow=0;
N=N/10;
while(N>0){
pow++;
int r=N%10;
N=N/10;
if(r>lsd){
// 递减
lsd=r-1;
// 均为9结尾
res=r*(int)Math.pow(10,pow)-1;
}else{
// 正常递增
lsd=r;
res+=r*(int)Math.pow(10,pow);
}
}
return res;
}
}