C++ O(Log(N)) Time O(Log(N)) Space


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.