题目:
我的解法:
class Solution {
public int monotoneIncreasingDigits(int N) {
Deque<Integer> queue = new LinkedList<Integer>();
int num = N;
int len = 0;
int ans = 0;
// 将整数N的每一位存到队列里
while(num!=0){
int res = num % 10;
queue.offer(res);
num = num/10;
len++;
}
// 依次从队列末尾取一个数字
while(queue.size()!=0){
int n = queue.pollLast();
int l = len;
int val = 0;
// 计算满足单调递增数字的最小情况,即后面的数与取出的数都相等
while(l>0){
val += n * Math.pow(10, l-1);
l--;
}
l = len;
// 如果N不满足单调递增的最小情况,则需要将当前取出的数字减1,后面所有位补9,返回结果
if(ans+val > N){
n--;
ans += n * Math.pow(10, l-1);
l--;
while(l>0){
ans += 9 * Math.pow(10, l-1);
l--;
}
return ans;
}else{// 如果N满足单调递增的最小情况,则直接保留当前位数字
ans += n * Math.pow(10, l-1);
}
len--;
}
return ans;
}
}
官方题解:
class Solution {
public int monotoneIncreasingDigits(int N) {
char[] strN = Integer.toString(N).toCharArray();
int i = 1;
while (i < strN.length && strN[i - 1] <= strN[i]) {
i += 1;
}
if (i < strN.length) {
while (i > 0 && strN[i - 1] > strN[i]) {
strN[i - 1] -= 1;
i -= 1;
}
for (i += 1; i < strN.length; ++i) {
strN[i] = '9';
}
}
return Integer.parseInt(new String(strN));
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/monotone-increasing-digits/solution/dan-diao-di-zeng-de-shu-zi-by-leetcode-s-5908/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。