題目:
輸入數(shù)字n慨绳,按順序打印出從1到最大的n位十進(jìn)制數(shù)。比如輸入3莫瞬,則打印輸出1儡蔓、2、3一直到最大的3位數(shù)即999
解法:
如果直接先求出最大的n位整數(shù)疼邀,可能會出現(xiàn)大整數(shù)問題喂江。
因此,只能通過字符串模擬大整數(shù)加法
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;
}