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]
.
Approach #1: C++. [recursive]
class Solution { public: int monotoneIncreasingDigits(int N) { stack<int> temp; while (N) { int lastNum = N % 10; N /= 10; temp.push(lastNum); } int curNum = temp.top(); temp.pop(); int ans = 0; while (!temp.empty()) { if (curNum <= temp.top()) { ans = ans * 10 + curNum; curNum = temp.top(); temp.pop(); } else { ans = ans * 10 + curNum - 1; for (int i = 0; i < temp.size(); ++i) ans = ans * 10 + 9; if (judge(ans)) return ans; else return monotoneIncreasingDigits(ans); } } ans = ans * 10 + curNum; return ans; } bool judge(int N) { int lastNum = N % 10; N /= 10; while (N) { int curNum = N % 10; N /= 10; if (curNum > lastNum) return false; lastNum = curNum; } return true; } };
Approach #2: Java. [Truncate After Cliff]
class Solution { public int monotoneIncreasingDigits(int N) { char[] S = String.valueOf(N).toCharArray(); int i = 1; while (i < S.length && S[i-1] <= S[i]) i++; while (0 < i && i < S.length && S[i-1] > S[i]) S[--i]--; for (int j = i+1; j < S.length; ++j) S[j] = '9'; return Integer.parseInt(String.valueOf(S)); } }