题目:
输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印输出1、2、3一直到最大的3位数即999
解法:
如果直接先求出最大的n位整数,可能会出现大整数问题。
因此,只能通过字符串模拟大整数加法
bool inc(char* str, int n) {
int carry = 1;
int carry_inex = n;
while (carry && carry_index >= 0) {
char tmp = str[carry_index] + 1;
if (tmp > '9') {
str[carry_index] = '0';
carry = 1;
--carry_index;
} else {
str[carry_index] = tmp;
carry = 0;
--carry_index;
}
}
return str[0] == '0';
}
void print(char *str, int n) {
bool flag = false;
for (int i = 0; i <= n; ++i) {
if (str[i] != 0 && flag == false) {
flag = true;
}
if (flag == true) {
cout << str[i];
}
}
cout << endl;
}
void printToMaxN(int n) {
char *str = new char[n+1];
memset(str, '0', n+1);
while (inc(str, n)) {
print(str, n);
}
delete []str;
}