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

Hint:
要找小于或等于一个数的,最大的单调递增数(高位不大于低位),显然是个贪心问题。
我们知道,尽量保证高位不减少或降幅尽可能小,则数字越大。
我们应该去首先考虑去修改低位,使低位变大。
因此从个位开始,如果低位小于其前一个高位,将这个高位-1,而使低位变成最大的‘9’。

class Solution {
public:
    int monotoneIncreasingDigits(int N) {
        stringstream ss;
        ss << N;
        string num;
        ss >> num;
        int k = num.size();
        for (int i = num.size()-1; i > 0; i--) {
            if (num[i] < num[i-1]) {
                k = i;
                num[i-1] -= 1;
            }
        }
        for (int i = k; i < num.size(); i++) {
            num[i] = '9';
        }
        ss.clear();
        ss << num;
        ss >> N;
        return N;
    }
};

猜你喜欢

转载自blog.csdn.net/ulricalin/article/details/78943479