Leetcode 738. Monotone Increasing Digits
Given a non-negative integer N
, you need to find the largest number that is less than or equal to N
and that its digits are in non-decreasing order (monotone increasing).
N
will be a non-negative integer and the standard range for an integer would be assumed.int N
int
Here is the C++ implementation of the described solution:
#include <iostream>
#include <string>
int monotoneIncreasingDigits(int N) {
std::string strN = std::to_string(N);
int n = strN.size();
int marker = n;
// Find the first place where the order is violated.
for (int i = n - 1; i > 0; --i) {
if (strN[i] < strN[i - 1]) {
marker = i;
strN[i - 1]--;
}
}
// Change all digits after the marker to '9'.
for (int i = marker; i < n; ++i) {
strN[i] = '9';
}
return std::stoi(strN);
}
int main() {
int N = 332;
std::cout << "The largest number less than or equal to " << N << " with monotone increasing digits is " << monotoneIncreasingDigits(N) << std::endl;
return 0;
}
d
be the number of digits in N
. We perform a constant amount of work (comparing, decrementing, setting to ‘9’) for each digit.d
is the number of digits in the integer N.d
is the number of digits in the integer N.This covers the strategy and solution to the problem, ensuring clarity and efficiency in implementation.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?