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

    Approach #1: C++. [recursive]

    class Solution {
    public:
        int monotoneIncreasingDigits(int N) {
            stack<int> temp;
    
            while (N) {
                int lastNum = N % 10;
                N /= 10;
                temp.push(lastNum);
            }
            
            int curNum = temp.top();
            temp.pop();
            
            int ans = 0;
            while (!temp.empty()) {
                if (curNum <= temp.top()) {
                    ans = ans * 10 + curNum;
                    curNum = temp.top();
                    temp.pop();
                } else {
                    ans = ans * 10 + curNum - 1;
                    for (int i = 0; i < temp.size(); ++i) 
                        ans = ans * 10 + 9;
                    if (judge(ans))
                        return ans;
                    else return monotoneIncreasingDigits(ans);
                }
            }
            ans = ans * 10 + curNum;
            return ans;
        }
        
        bool judge(int N) {
            int lastNum = N % 10;
            N /= 10;
            while (N) {
                int curNum = N % 10;
                N /= 10;
                if (curNum > lastNum) return false;
                lastNum = curNum;
            }
            
            return true;
        }
    };
    

      

    Approach #2: Java. [Truncate After Cliff]

    class Solution {
        public int monotoneIncreasingDigits(int N) {
            char[] S = String.valueOf(N).toCharArray();
            int i = 1;
            while (i < S.length && S[i-1] <= S[i]) i++;
            while (0 < i && i < S.length && S[i-1] > S[i]) S[--i]--;
            for (int j = i+1; j < S.length; ++j) S[j] = '9';
    
            return Integer.parseInt(String.valueOf(S));
        }
    }
    

      

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    poj-2478 Farey Sequence(dp,欧拉函数)
    codeforces 515C C. Drazil and Factorial(水题,贪心)
    hdu-5643 King's Game(打表)
    可以在命令行直接使用密码来进行远程连接和远程拉取文件的命令:sshpass
    查看SQL运行时间
    管理kafka
    No module named _sqlite3
    ps
    Redis之RDB与AOF
    Redis 4 参数解释
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10246849.html
Copyright © 2020-2023  润新知