leetcode 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 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

题目给出一个数字N,让输出一个<=N小,而且要逐位升序(包括相等)的数字
图中example3,如果输出=N的数字,因为N中后面两位是降序的,所以要想升序,只能最大299

思路:
N如果是个位数,直接输出N就可以了

N的位数>=2时,类似31.Next Permutation的思路
31题因为数字是固定的,只能调换顺序,所以找到降序的位置,和降序后面的仅比它大的数字交换,然后降序后面的部分升序排列

此题因为不需要固定数字,同样也是找到降序的地方,降序后面的部分直接全部换成最大的9

**为了方便数字逐位操作,把int型数字转化成char数组
注意降序后面换成9的部分
比如332,检测到降序的index是i=2
这时候应该把index前面的一位 j 数字 -1. 变成322

因为输出的结果中不能有降序的数字,所以遇到降序仍然往前 -1
这时候j指向2,j的前面一位3仍然>2
再把j前面一位-1, 变成222
这时候从现在的j+1开始到后面全部变成9,即299
int j = i;
while (j >= 1 && num[j] < num[j - 1]) {

//1ms
    public int monotoneIncreasingDigits(int N) {
        if (N < 10) {
            return N;
        }
        
        char[] num = String.valueOf(N).toCharArray();
        int index = num.length;
        
        for (int i = 1; i < num.length; i++) {
            if (num[i - 1] > num[i]) {
                int j = i;
                while (j >= 1 && num[j] <  num[j - 1]) {
                    num[--j] --;
                }
                index = j + 1;
                break;
            }
        }
        
        for (int j = index; j < num.length; j ++) {
            num[j] = '9';
        }
        
        return Integer.parseInt(String.valueOf(num));
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值