创作目的:为了方便自己后续复习重点,以及养成写博客的习惯。
思路:参考carl文档
????????当strNum[i - 1] > strNum[i](非单调递增),先让strNum[i - 1]--,再strNum[i]=9。再确定是从后向前遍历。
ledcode题目:https://leetcode.cn/problems/monotone-increasing-digits/
AC代码:
void itoa(int num, char* str, int* strSize) {
*strSize = 0;
while (num > 0) {
str[(*strSize)++] = num % 10 + '0';
num /= 10;
}
for (int i = 0; i < (*strSize) / 2; i++) {
int tmp = str[i];
str[i] = str[(*strSize) - 1 - i];
str[(*strSize) - 1 - i] = tmp;
}
}
int monotoneIncreasingDigits(int n) {
int strNSize;
char strN[11];
itoa(n, strN, &strNSize);
int i = 1;
while (i < strNSize && strN[i - 1] <= strN[i]) {
i += 1;
}
if (i < strNSize) {
while (i > 0 && strN[i - 1] > strN[i]) {
strN[i - 1] -= 1;
i -= 1;
}
for (i += 1; i < strNSize; ++i) {
strN[i] = '9';
}
}
return atoi(strN);
}