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;
}
};