-
-
Notifications
You must be signed in to change notification settings - Fork 524
/
Copy pathSolution.java
61 lines (56 loc) · 1.31 KB
/
Solution.java
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
/**
* @author bingo
* @since 2018/12/18
*/
class Solution {
/**
* 打印从1到最大的n位数
*
* @param n n位数
*/
public void print1ToMaxOfNDigits(int n) {
if (n < 1) {
return;
}
char[] chars = new char[n];
Arrays.fill(chars, '0');
while (increment(chars)) {
printNumber(chars);
}
}
/**
* 打印字符数组表示的数字(需要省略前n个0)
*
* @param chars 字符数组
*/
private void printNumber(char[] chars) {
int i = 0, n = chars.length;
for (; i < n; ++i) {
if (chars[i] != '0') {
break;
}
}
StringBuilder sb = new StringBuilder();
for (; i < n; ++i) {
sb.append(chars[i]);
}
System.out.println(sb.toString());
}
private boolean increment(char[] chars) {
int n = chars.length;
int carry = 1;
for (int i = n - 1; i >= 0; --i) {
int sum = chars[i] - '0' + carry;
if (sum > 9) {
if (i == 0) {
return false;
}
chars[i] = '0';
} else {
++chars[i];
break;
}
}
return true;
}
}