738. Monotone Increasing Digits

本文介绍了一种算法,用于找到小于等于给定非负整数N的最大单调递增数字。通过提取N的各位数字并检查其是否递增,算法在遇到非递增情况时进行调整,最终返回调整后的最大单调递增数字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Note: N is an integer in the range [0, 10^9].

import java.util.ArrayList;
import java.util.List;
class Solution {
    public int monotoneIncreasingDigits(int N) {
        // 提取出整数N各位上的数字
        List<Integer> digits = new ArrayList<>();
        while (N >= 10) {
            digits.add(0,N%10);
            N /= 10;
        }
        digits.add(0, N);

        // 检查当前各位数字是否递增
        while (!checkValid(digits)) {
            // 如遇到非递增的情况,调整
            transform(digits);
        }
        // 若首位数字为0,删除
        while (digits.get(0) == 0) {
            digits.remove(0);
        }
        // 将各位上的数字组装成一个整数
        String strResult = "";
        for (int dgt :digits) {
            strResult += dgt;
        }
        return Integer.valueOf(strResult);
    }

    private void transform(List<Integer> digits) {
        int pre = digits.get(0);
        // 从首向尾遍历,找出首次出现非递增的一对数
        for (int i = 1; i < digits.size(); i++) {
            if (digits.get(i) < pre) {
                digits.set(i-1, pre-1);
                for (int j = i; j < digits.size(); j++) {
                    digits.set(j, 9);
                }
                break;
            }
            pre = digits.get(i);
        }
    }

    // 检查是否递增
    private boolean checkValid(List<Integer> digits) {
        int pre = -1;
        for (int d : digits) {
            if (pre > d) {
                return false;
            }
            pre = d;
        }
        return true;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值