Monotone Increasing Digits

本文介绍了一道关于寻找最大递增数字的问题,并提供了一个使用贪心算法解决该问题的C++实现方案。通过扫描数字并调整使其保持递增状态,确保结果是最接近原数的最大递增数字。

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

Monotone Increasing Digits

A.题意

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

这道题题意大致是让你从给定的数字范围内选一个最大的递增数字

B.思路

这道题应该就是贪心算法了,从后向前扫描这个数字遇到后面比前面小的前面数字减一并且后面全部变成9,要保证这是数字中最前面的满足上面说的那个条件的位置。

C.代码实现

class Solution {
public:
    int monotoneIncreasingDigits(int N) {
        string str = to_string(N);
        int n = str.size(), j = n;
        for (int i = n - 1; i > 0; i--)
        {
            if (str[i] >= str[i - 1])
            {
                continue;
            }
            else {
                str[i - 1]--;
                j = i;
            }
        }
        for (int i = j;i < n;i++)
        {
            str[i] = '9';
        }
        return stoi(str);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值