输入数字n,按顺序打印出从1到最大的n位十进制数,比如输入3,则打印出1、2、3....999。
思路:由于n的大小不一定,所以可能long long也存不下。
1、模拟法,利用字符串模拟加法操作
2、全排列,利用递归处理
代码一(模拟):
bool increment(char *s, int n)
{
s[0]++;
int t = 0;
while(s[t] > '9')
{
s[t] = '0';
s[++t] ++;
}
if(t == n) return false;
return true;
}
void print(char *s, int n)
{
int i, j;
for(i = n-1; s[i] == '0' && i >= 0; i--);
for(j = i; j >= 0; j--)
cout << s[j];
cout << endl;
}
void printN(int n)
{
char *s = new char[n+1];
for(int i = 0; i < n; i++) s[i] = '0';
s[n] = 0;
while(increment(s, n))
{
print(s, n);
}
}
代码二(全排列):
void find(char *s, int now, int n)
{
if(now == n)
{
int i;
for(i = 0; s[i] == '0' && i < n; i++);
if(i != n) cout << s+i << endl;
return;
}
for(char i = '0'; i <= '9'; i++)
{
s[now] = i;
find(s, now+1, n);
}
}
void get(int n)
{
char *s = new char[n+1];
s[n] = 0;
find(s, 0, n);
}