题目:输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1,2,3一直到最大的3位即999.
这个题目看着简单,我们一般想到的是:
package Stringchar;
public class PrintNumberMain {
public void PrintToNumber(int n) {
int num = 1;
int i = 0;
while (i < n) {
num *= 10;
i++;
}
for (int j = 0; j < num; j++) {
System.out.print(j + " ");
}
}
public static void main(String[] args) {
PrintNumberMain printNumberMain = new PrintNumberMain();
printNumberMain.PrintToNumber(3);
}
}
但是我们没有考虑到当输入的n很大时,就会溢出。也就是说我们需要考虑大数问题。这也是面试官设置的陷阱。
我们可以考虑用字符串来模拟数字加分的解法,绕过陷阱才能拿到Offer。
其代码如下:
public void PrintToNumber2(int n) {
if (n < 0)
return;
char[] num = new char[n];
for (int i = 0; i < n - 1; i++)
num[i] = '0';
num[n - 1] = '\0';
while (!Increament(num)) {
PrintNumber(num);
}
}
public void PrintNumber(char[] num) {
boolean isBeginning0 = true;
int nlength = num.length;
for (int i = 0; i < nlength; i++) {
if (isBeginning0 && num[i] != '\0') {
isBeginning0 = false;
}
if (!isBeginning0) {
System.out.print(num[i]);
}
}
System.out.print("\t");
}
public boolean Increament(char[] num) {
boolean isOverflow = false;
int nTakeOver = 0;
int nLength = num.length;
for (int i = nLength - 1; i >= 0; i--) {
int nSum = num[i] - '0' + nTakeOver;
if (i == nLength - 1)
nSum++;
if (nSum >= 10) {
if (i == 0)
isOverflow = true;
else {
nSum -= 10;
nTakeOver = 1;
num[i] = (char) (nSum + '0');
}
} else {
num[i] = (char) ('0' + nSum);
break;
}
}
return isOverflow;
}
把问题转换为数字排列的解法,递归让代码更简洁:
public void PrintToNumber3(int n) {
if (n < 0)
return;
char[] num = new char[n + 1];
num[n] = '\0';
for (int i = 0; i < 10; i++) {
num[0] = (char) (i + '0');
PrintNumberRecursive(num, n, 0);
}
}
public void PrintNumberRecursive(char[] num, int n, int index) {
if (index == n - 1) {
PrintNumber(num);
return;
}
for (int i = 0; i < 10; i++) {
num[index + 1] = (char) (i + '0');
PrintNumberRecursive(num, n, index + 1);
}
}