题目:输入数字n,按顺序打印出从1最大的n位十进制数。
思路:n没有范围,可能出现大数,采用字符串或者数组表达大数。
#include <exception>
#include <iostream>
using namespace std;
void PrintNumber(char *number) {
bool isBegining0 = true;
int nLength = strlen(number);
for (int i = 0; i < nLength; i++) {
if (isBegining0 && number[i] != '0')
isBegining0 = false;
if (!isBegining0)
cout << number[i];
}
}
void Print1ToMaxRecursively(char *number, int nLength, int index) {
if (index == nLength - 1) {
PrintNumber(number);
cout << " ";
return;
}
for (int i = 0; i < 10; i++) {
number[index + 1] = i + '0';
Print1ToMaxRecursively(number, nLength, index + 1);
}
}
void Print1ToMax(int n) {
if (n <= 0)
return;
char *number = new char[n + 1];
number[n] = '\0';
for (int i = 0; i < 10; i++) {
number[0] = i + '0';
Print1ToMaxRecursively(number, n, 0);
}
delete[] number;
}
int main() {
int n = 3;
Print1ToMax(n);
return 0;
}