738. Monotone Increasing Digits
LInk: https://leetcode.com/problems/monotone-increasing-digits/
Description
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.
Approach
- Split the integer
n
into digits. - Loop the digits from end to start:
- If the current digit smaller than the previous digit, decrement the previous digits and save the index of the current digit.
- Loop the digits from the saved index to the end, let the digit equal to 9.
Solution
class Solution {
public int monotoneIncreasingDigits(int n) {
String[] nums = (n + "").split("");
int start = nums.length;
for (int i = nums.length - 1; i > 0; i --) {
if (Integer.parseInt(nums[i - 1]) > Integer.parseInt(nums[i])) {
start = i;
nums[i - 1] = (Integer.parseInt(nums[i - 1]) - 1) + "";
}
}
for (int i = start; i < nums.length; i++) {
nums[i] = "9";
}
return Integer.parseInt(String.join("", nums));
}
}