[LeetCode] Monotone Increasing Digits

738. Monotone Increasing Digits

An integer has monotone increasing digits if and only if each pair of adjacent digits x and y satisfy x <= y.

Given an integer n, return the largest number that is less than or equal to n with monotone increasing digits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int monotoneIncreasingDigits(int n) {
string s = to_string(n);
int len = s.length();
bool mono = true;
for(int i = 0; i < len - 1 and mono; i++) {
if(s[i] > s[i + 1]) mono = false;
}
if(mono) return n;

for(int i = 0; i < len - 1; i++) {
if(s[i] > s[i + 1]) {
char v = s[i];
int j = i;
while(j - 1 >= 0 and s[j - 1] == v) j--;
s[j] -= 1;
j += 1;
for(; j < len; j++)
s[j] = '9';
break;
}
}

return stoi(s);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/23/PS/LeetCode/monotone-increasing-digits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.