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


首先将给定的数字转换成字符串
应用贪心策略,查找第一个比下一位小的位置,这样就能保证在这一位以前,均为升序排列,而对于这一位,退位(s[i]-1)操作,再将剩余位置用9填充。
如果在字符串中出现 当前位数与下一位相等 的情况,记录这个其第一次出现的位置,退位时也在其第一次出现的位置退位,并以9填充


class Solution {
private:
    int strTonum(string s){
        int ans=0;
        int len=s.size();
        for(int i=0;i<len;i++)
            ans=ans*10+(s[i]-'0');
        return ans;
    }
    string numTostr(int N,int dig){
        string ans(dig,'+');
        int pos=dig-1;
        while(N){
            char c=N%10+'0';
            ans[pos]=c;
            pos--;
            N/=10;
        }
        return ans;
    }
    int numOfDigit(int N){
        int num=0;
        while(N){
            num++;
            N/=10;
        }
        return num;
    }
public:
    int monotoneIncreasingDigits(int N) {
        if(N<10)
            return N;
        int len=numOfDigit(N);
        string num=numTostr(N,len);
        int index=-1;
        string temp(len,'0');
        bool flag=false;
        for(int i=0;i<len-1;i++){
            if(num[i]<num[i+1]){
                index=i;
                temp[i]=num[i];
            }else{
                if(num[i]==num[i+1]){
                    temp[i]=num[i];
                    continue;
                }
                else{
                    index++;
                    temp[index]=num[i]-1;
                    index++;
                    flag=true;
                    break;
                }
            }
        }
        if(!flag)
            return N;
        else{
            for(int i=index;i<len;i++)
                temp[i]='9';
            return strTonum(temp);
        }
    }
};

测试样例

test:567321
ans:566999

test:23344551
ans:23344499

test:54321
ans:49999

test:120
ans:119

test:0
ans:0

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值