[LeetCode]--Monotone Increasing Digits

题目

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

中文题意:找到不超过给定数N的最大的递增数。递增数是指后一位大于或等于前一位的数。

分析

   由于对整数中单个数位的处理较为繁琐,因此,本题中先把所给整数转换为string类型,对于每一个char字符进行处理,这样可以减少计算量,在最终通过stoi函数将string转为整型数即可。
      首先遍历字符串的每一位,从原数字的高位开始,若前一位不大于后一位,则证明整数N已经是一个递增数,直接返回整数N即可;若前一位大于后一位,则跳出遍历,处理其后的所有数位。
      对于所给整数中不满足条件的数位,我们先记录不满足条件的位置,然后将最高的与该位置数值相同的数位的数值减1,再将其后所有数位设置为9(如例3)。这样既满足了递增数的要求,又满足了最大递增数的条件。
      此算法的时间复杂度为O(n),其中n为整数的位数。

解答

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



猜你喜欢

转载自blog.csdn.net/weixin_38057349/article/details/79118934