注:此博客不再更新,所有最新文章将发表在个人独立博客limengting.site。分享技术,记录生活,欢迎大家关注
题目描述:
输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1\2\3一直到最大的3位数299
思路一:考虑大数用String表示,考虑从第一个不为0的数字开始输出
public class Print1ToMaxOfNDigits {
public static void Print1ToMaxOfNDigits(int n) {
if (n <= 0) return;
StringBuffer number = new StringBuffer();
for (int i = 0; i < n; i++)
number.append('0');
while (!Increment(number))
PrintNumber(number);
}
public static boolean Increment(StringBuffer sb) {
boolean isOverflow = false;
int nTakeOver = 0;
int nLength = sb.length();
// Index increase from left to right, index of left-most is 0, index of right-most is nLength - 1
for (int i = nLength - 1; i >= 0; i--) {
int nSum = sb.charAt(i) - '0' + nTakeOver;
if (i == nLength - 1) nSum++; // the first num is 1 not 0
if (nSum >= 10) {
if (i == 0) {
isOverflow = true;
} else {
nSum -= 10;
nTakeOver = 1;
sb.setCharAt(i, (char) ('0' + nSum));
}
} else {
sb.setCharAt(i, (char) ('0' + nSum));
break;
}
}
return isOverflow;
}
public static void PrintNumber(StringBuffer sb) {
boolean isBeginningWith0 = true;
for (int i = 0; i < sb.length(); i ++) {
if (isBeginningWith0 && sb.charAt(i) != '0') { // when first come to the not 0 num
isBeginningWith0 = false;
}
if (!isBeginningWith0)
System.out.print(sb.charAt(i));
}
System.out.println();
}
public static void main(String[] args) {
Print1ToMaxOfNDigits(100);
}
}
思路二:用数字排列的方法表示:如果我们在数字前面补0的话,就会发现n位所有十进制数其实就是n个从0到9的全排列。也就是说,我们把数字的每一位都从0到9排列一遍,就得到了所有的十进制数。当然打印的时候,我们应该将前面的0补位去掉。
public class Print1ToMaxOfNDigits {
public static void Print1ToMaxOfNDigits(int n) {
if (n <= 0) return;
StringBuffer sb = new StringBuffer(n);
for (int i = 0; i < n; i ++)
sb.append('0');
for (int i = 0; i < 10; i ++) {
sb.setCharAt(0, (char) (i + '0'));
print1ToMaxOfNDigitsRecursively(sb, n, 1);
}
}
public static void print1ToMaxOfNDigitsRecursively(StringBuffer sb, int n , int index) {
if (index == n) {
PrintNumber(sb);
return;
}
for (int i = 0; i < 10; i ++) {
sb.setCharAt(index, (char) (i + '0'));
print1ToMaxOfNDigitsRecursively(sb, n, index + 1);
}
}
public static void PrintNumber(StringBuffer sb) {
boolean isBeginningWith0 = true;
for (int i = 0; i < sb.length(); i ++) {
if(isBeginningWith0 && sb.charAt(i) != '0')
isBeginningWith0 = false;
if (!isBeginningWith0) {
System.out.print(sb.charAt(i));
}
}
System.out.println();
}
public static void main(String[] args) {
Print1ToMaxOfNDigits(100);
}
}