-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonotoneIncreasingDigits.java
More file actions
79 lines (70 loc) · 2.4 KB
/
MonotoneIncreasingDigits.java
File metadata and controls
79 lines (70 loc) · 2.4 KB
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package leetcode;
/**
* MonotoneIncreasingDigits
* https://leetcode-cn.com/problems/monotone-increasing-digits/
* 738. 单调递增的数字
*
* @author tobin
* @since 2020-12-15
*/
public class MonotoneIncreasingDigits {
public static void main(String[] args) {
MonotoneIncreasingDigits sol = new MonotoneIncreasingDigits();
System.out.println(sol.monotoneIncreasingDigits(10));
System.out.println(sol.monotoneIncreasingDigits(1234));
System.out.println(sol.monotoneIncreasingDigits(4321));
System.out.println(sol.monotoneIncreasingDigits(120));
System.out.println(sol.monotoneIncreasingDigits(332));
}
public int monotoneIncreasingDigits(int N) {
if (N < 10) {
return N;
}
int[] digits = new int[10];
int tmp = N;
int idx = 0;
while (tmp > 0) {
digits[idx] = tmp % 10;
tmp /= 10;
idx++;
}
int size = idx;
boolean lostRelate = false;
for (idx = size - 1; idx >= 0; idx--) {
if (lostRelate) {
digits[idx] = 9;
} else if (idx + 1 >= size) {
// first num
} else {
// borrow from higher digits
boolean mustBorrow = false;
while (idx + 1 < size) {
// 当前位置不小于上一个位置, 取值即可
if (!mustBorrow && digits[idx] >= digits[idx + 1]) {
// available, use origin num
break;
}
mustBorrow = false;
// 当前位置小于上一个位置, 需要向上一个位置借1
digits[idx] = 9;
if (digits[idx + 1] > 0) {
// 上一个位置-1
digits[idx + 1]--;
} else {
// 0, 上一个位置需要再向上两个位置借1
mustBorrow = true;
}
// 后退下标, 迭代判断
idx++;
// once borrow, left are 9s
lostRelate = true;
}
}
}
int result = 0;
for (idx = size - 1; idx >= 0; idx--) {
result = result * 10 + digits[idx];
}
return result;
}
}