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

思路:这题要求求出给定比N小的第一个每一个数字都是增序排列的数字,假如遍历的话时间肯定是不够的,那么我们就只能找规律了,我们发现比给定数字小的第一个增序数字由三部分组成,第一部分为原数字从高位到低位增序排列的几个数字,第二部分为原数字相应位置数字减一,第三部分全是9,因此我们可以把原数字转换成string类型,从高位向低位找到第一个非增序数字,然后从这个位置开始为第二部分和第三部分。

class Solution {

    #include <string>

public:

    int monotoneIncreasingDigits(int N) {

       int temp; int Nz = N;

      string num = "";

      if (N == 0) return 0;

      while (Nz != 0)

      {

            temp = Nz % 10;

            char a = temp + 48;

            num = a+num;

            Nz = Nz / 10;

      }

      if (num.size() == 1) return temp;

      int i;

      for (i = 1; i<num.size(); i++)

      {

            if (!(num[i] >= num[i - 1]))

            break;

      }

      if (i == num.size()) return N;

      int j;

            for (j = i - 1; j >= 0; j--)

            {

                  if (j == 0)break;

                       if (!(num[j - 1] ==num[j])) {  break; }

            }

      Nz = 0;

      for (i = 0; i<j; i++)

            Nz = (Nz * 10 + num[i] - 48);

      Nz = (Nz*10+num[j] - 1 - 48);

      for (i = j+1; i <= num.size()-1; i++)

            Nz = (Nz * 10 + 9);

 

     

      return Nz;

    }

};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值