[leetcode]738. Monotone Increasing Digits

[leetcode]738. Monotone Increasing Digits


Analysis

放假回家效率果然打折—— [每天刷题并不难0.0]

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.)
在这里插入图片描述

Explanation:

找出小于N的最大数,保证该数的每个数字是递增的~

Implement

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

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/86686692