两种解法,一种递归,一种判断该数加1是否最高位进1
第二种较简单
主要两个函数,一个是打印数字,要求判断该数字是否是第一个不为零的数字,然后后面的依次打出即可
第二个函数是对一个数加1判断加1之后的数是否使得最高位进位
初始化长度为n的字符数组,即初始0,对该数实现字符上的加1,如果一直没进位,则打印该数,如果进位,则退出循环
第二种利用递归,全排列的思想
从左到右,由高位开始,0到9排列,0的情况递归到深一层,继续0到9
递归结束的条件是到了最后一位,也就是最右边的一位
package print1ToMaxOfNDigits12;
public class Sol2 {
static void printNumber(char[] numbers) {
boolean beginIs0 = true;
for (int i = 0; i < numbers.length; i++) {
if (beginIs0 && numbers[i] != ‘0’) {
beginIs0 = false;
}
if (!beginIs0) {
System.out.print(numbers[i]);
}
}
System.out.println();
}
static boolean increment(char[] numbers) {
boolean isOverflow = false;
int length = numbers.length;
int carry = 0;
for (int i = length – 1; i >= 0; i–) {
int sum = numbers[i] – ‘0’ + carry;
if (i == length – 1) {
sum++;
}
if (sum >= 10) {
if (i == 0) {
isOverflow = true;
} else {
sum -= 10;
carry = 1;
numbers[i] = (char) (‘0’ + sum);
}
} else {
numbers[i] = (char) (‘0’ + sum);
break;
}
}
return isOverflow;
}
static void myPrint(int n) {
if (n <= 0) {
return;
}
char[] numbers = new char[n];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = ‘0’;
}
while (!increment(numbers)) {
printNumber(numbers);
}
}
public static void main(String[] args) {
// printNumber(“001”.toCharArray());
myPrint(2);
}
}
package print1ToMaxOfNDigits12;
public class Print1ToMaxOfNDigits12 {
static void myPrint(int n) {
if (n <= 0) {
return;
}
char[] numbers = new char[n];
for (int i = 0; i < 10; i++) {
numbers[0] = (char) (i + ‘0’);
printRecursively(numbers, n, 0);
}
}
static void printNumber(char[] numbers) {
boolean beginIs0 = true;
for (int i = 0; i < numbers.length; i++) {
if (beginIs0&&numbers[i] != ‘0’) {
beginIs0 = false;
}
if (!beginIs0) {
System.out.print(numbers[i]);
}
}
System.out.println();
}
private static void printRecursively(char[] numbers, int length, int index) {
if (index==length-1) {
printNumber(numbers);
return;
}
for (int j = 0; j < 10; j++) {
numbers[index+1]=(char) (j+’0′);
printRecursively(numbers, length, index+1);
}
}
public static void main(String[] args) {
myPrint(2);
}
}