leetcode 738 单调递增数字位

本文介绍了一种算法,用于找到小于或等于给定非负整数N的最大数值,该数值的数字具有单调递增特性。通过实例展示了算法的运行过程,并提供了Python和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
Note: N is an integer in the range [0, 10^9].
题解:
我们只需要找到最左边出现逆序的数字所在位即可,将这个数字-1,这个数字后面的位全变为9
注意一种比较极端的情况,就是当14444687
python code:
def monotoneIncreasingDigits(self, N):
“”"
:type N: int
:rtype: int
“”"
s=list(str(N))
maker=len(s)
for i in xrange(maker-1,0,-1):
if s[i]<s[i-1]:
maker,s[i-1]=i,str(int(s[i-1])-1)
s[maker:]=[‘9’]*(len(s)-maker)
return int(’’.join(s))
c++ code:
class Solution {
public:
int monotoneIncreasingDigits(int N) {
string s=to_string(N);
int maker=s.size();
for(int i=s.size()-1;i>0;i–)
{
if(s[i]<s[i-1])
{
maker=i;
s[i-1]=s[i-1]-1;
}
}
for(int i=maker;i<s.size();i++) s[i]=‘9’;
return stoi(s);
}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值