738. Monotone Increasing Digits

本文介绍了一种算法问题,即给定一个非负整数N,找到小于等于N的最大整数,该整数的数字为单调递增。通过示例说明了如何使用贪心算法解决这一问题,并给出了C++实现代码。

摘要生成于 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

这题暴力解法就是一个个数check,超时。
贪心算法,构造需要的解去试。
key point就是,如果已知现有的部分是‘123’,下一个数字最大可以是多少了?比如5,那么就要保证1235…5 <= N。在这个要求下去找每一位可能的数字就行。
代码:

class Solution {
public:
    int monotoneIncreasingDigits(int N) {
        string res = "";
        string num = to_string(N);
        for (int i = 0; i < num.size(); i++) {
            int flag = false;
            for (char c = '1'; c <= '9'; c++) {
                string temp= res;
                while (temp.size() < num.size()) temp += c;
                if (temp > num) {
                    res += c - 1;
                    flag = true;
                    break;
                }
            }
            if (flag == false) res += '9';
        }
        return stoi(res);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值