问题:
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 = 10Output: 9
Example 2:
Input: N = 1234Output: 1234
Example 3:
Input: N = 332Output: 299
Note: N
is an integer in the range [0, 10^9]
.
解决:
① 给定整数N,求不大于N的最大整数,其各位数单调不减。
从高位向低位遍历整数N的各位数,找到第一个违反单调不减的数的下标x,将x位上的数-1,将x位后的所有数替换为9.
class Solution { //22ms
public int monotoneIncreasingDigits(int N) { String s = String.valueOf(N); char[] schar = s.toCharArray(); int len = schar.length; int j = len; for (int i = len - 1;i > 0;i --){ if (schar[i] >= schar[i - 1]) continue; schar[i - 1]--; j = i; } for (int i = j;i < len;i ++){ schar[i] = '9'; } return Integer.parseInt(String.valueOf(schar)); } }