LC 738. Monotone Increasing Digits

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 ysatisfy 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].

 

 

Runtime: 16 ms, faster than 87.76% of Java online submissions for Monotone Increasing Digits.

 

class Solution {
  public static int monotoneIncreasingDigits(int N) {
    char[] Nstr = String.valueOf(N).toCharArray();
    int cnt = 0;
    boolean firstmeet = true;
    while(cnt < Nstr.length-1){
      if(Nstr[cnt] > Nstr[cnt+1]){
        if(firstmeet) {
          for(int i=cnt+1; i<Nstr.length; i++) Nstr[i] = '9';
          Nstr[cnt] = (char)((int)Nstr[cnt] - 1);
          firstmeet = false;
        }else{
          Nstr[cnt+1] = '9';
        }
        if(cnt > 0) {
          cnt-=2;
          firstmeet = true;
        }
      }
      cnt++;
    }
    return Integer.parseInt(String.valueOf(Nstr));
  }
}

 

posted @ 2019-01-16 14:16  yuxihong  阅读(207)  评论(0编辑  收藏  举报