0
点赞
收藏
分享

微信扫一扫

[leetcode] 738. Monotone Increasing Digits

Soy丶sauce 2022-08-11 阅读 32


Description

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

分析

题目的意思是:找出0~N中,数字中的每个字符呈非递减顺序的最大值。

  • 从后往前遍历的最后一个值升高的位置,让前一位减1,并把当前位以及后面的所有位都变成9,就可以得到最大的单调递增数啦。

代码

class Solution {
public:
int monotoneIncreasingDigits(int N) {
string s=to_string(N);
int n=s.size();
int j=n;
for(int i=n-1;i>0;i--){
if(s[i]>=s[i-1]) continue;
s[i-1]--;
j=i;
}
for(int i=j;i<n;i++){
s[i]='9';
}
return stoi(s);
}
};

参考文献

​​[LeetCode] Monotone Increasing Digits 单调递增数字​​


举报

相关推荐

0 条评论