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

### Solution：

#include <iostream>
#include <cmath>
using namespace std;

int monotoneIncreasingDigits(int N) {
int i = 0;          // 记录需要调整的位置
int j = 0;          // 位数
bool flag = 0;      // 标记是否是转折点
int n = N;
int m1 = n % 10;    // 末位数
n = n / 10;
while (n) {
j++;
int m2 = n % 10;// 倒数第二个数
if (m1 < m2) {
flag = 1;
i = j;
} else {
if (flag && m1 == m2) i = j;
else flag = 0;
}
m1 = m2;
n /= 10;
}
return i == 0 ? N : ((N / int(pow(10, i)) - 1) * pow(10, i)
+ int(pow(10, i)) - 1);
}

int main() {
int N;
while (cin >> N) {
cout << monotoneIncreasingDigits(N) << endl;
}
system("pause");
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120