转载请注明作者与出处:franciscolv http://www.cnblogs.com/franciscolv/archive/2011/11/20/2255834.html
N位数打印需要注意越界问题。考虑到int或long的范围有界,所以采用字符数组的方式去打印。这里注意打印的时候每固定个值换行便于查看。
package SortSet;
/**
* 打印N位数
*
* @author franciscolv
*
*/
public class NPrint {
private static int count =0;
public static void main(String[] args) {
print(10);
}
public static void print(int n) {
if (n <= 0)
return;
char[] c = new char[n];
for (int i = 0; i < 10; i++) {
c[0] = (char) (i + '0');
print0(c, n, 0);
}
}
private static void print0(char[] c, int len, int n) {
if (n == len - 1) {
print1(c);
return;
}
for (int i = 0; i < 10; i++) {
c[n + 1] = (char) ('0' + i);
print0(c, len, n + 1);
}
}
private static void print1(char[] c) {
boolean isZero = true;
for (int i = 0; i < c.length; i++) {
if (isZero && c[i] != '0')
isZero = false;
if (!isZero)
System.out.print(c[i]);
}
count++;
if(count%50==0)
System.out.println();
else
System.out.print(" ");
}
}