static void print(int n) throws Exception {
char[] num = new char[n];
while (!increment(num)) {
printNum(num);
}
}
static void printNum(char[] num) {
for (int i = 0; i < num.length; i++) {
if (num[i]!='\u0000') {
System.out.print(num[i]);
}
}
System.out.println();
}
static boolean increment(char[] num) throws Exception {
int takeOver = 0;
for (int i = num.length - 1; i >= 0; i--) {
if (num[i] == '\u0000') {
num[i] = '0';
}
int number = Integer.parseInt(String.valueOf(num[i]));
int next = number + takeOver;
if (i == num.length - 1) {
next++;
}
if (next >= 10) {
if (i == 0) {
return true;
} else {
next -= 10;
if (next == 0) {
num[i] = '0';
} else if (next == 1) {
num[i] = '1';
} else {
throw new Exception("do not execute num:" + next);
}
takeOver = 1;
}
} else {
num[i] = Integer.toString(next).charAt(0);
break;
}
}
return false;
}
public static void main(String[] args) throws Exception {
print(1);
}
剑指offer12——打印1到最大的n位数
最新推荐文章于 2019-05-14 21:14:04 发布