題目:輸入數(shù)字n,按順序打印出從1到最大的n位十進(jìn)制數(shù)踪宠。比如輸入3步势,則打印出1氧猬、2背犯、3一直到最大的3位數(shù)999。
練習(xí)地址
https://leetcode-cn.com/problems/da-yin-cong-1dao-zui-da-de-nwei-shu-lcof/
方法1:遍歷
public void print1ToMaxOfNDigits(int n) {
if (n <= 0) {
return;
}
char[] number = new char[n];
for (int i = 0; i < n; i++) {
number[i] = '0';
}
while (!increment(number)) {
printNumber(number);
}
}
private boolean increment(char[] number) {
int takeOver = 0;
int length = number.length;
for (int i = length - 1; i >= 0; i--) {
int sum = number[i] - '0' + takeOver;
if (i == length - 1) {
sum++;
}
if (sum >= 10) {
if (i == 0) {
return true;
} else {
sum -= 10;
takeOver = 1;
number[i] = (char) ('0' + sum);
}
} else {
number[i] = (char) ('0' + sum);
break;
}
}
return false;
}
private void printNumber(char[] number) {
boolean isBegin0 = true;
int length = number.length;
for (int i = 0; i < length; i++) {
if (isBegin0 && number[i] != '0') {
isBegin0 = false;
}
if (!isBegin0) {
System.out.print(number[i]);
}
}
if (!isBegin0) {
System.out.println();
}
}
方法2:遞歸
public void print1ToMaxOfNDigits(int n) {
if (n <= 0) {
return;
}
char[] number = new char[n];
for (int i = 0; i < 10; i++) {
number[0] = (char) (i + '0');
print1ToMaxOfNDigitsRecursively(number, n, 0);
}
}
private void print1ToMaxOfNDigitsRecursively(char[] number, int length, int index) {
if (index == length - 1) {
printNumber(number);
return;
}
for (int i = 0; i < 10; i++) {
number[index + 1] = (char) (i + '0');
print1ToMaxOfNDigitsRecursively(number, length, index + 1);
}
}
private void printNumber(char[] number) {
boolean isBegin0 = true;
int length = number.length;
for (int i = 0; i < length; i++) {
if (isBegin0 && number[i] != '0') {
isBegin0 = false;
}
if (!isBegin0) {
System.out.print(number[i]);
}
}
if (!isBegin0) {
System.out.println();
}
}