# 打印1到最大的n位数 12

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);

}

}

原文作者：keedor
原文地址: https://www.cnblogs.com/keedor/p/4382183.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。