因为unsigned int甚至unsigned long类型不一定能表示很大的n位数,它们的表示范围是一定的,所以可以使用字符串来存储,并打印
bool Incerment(char*& str,int n)//每次调用这个函数都会对字符串进行数值的加1
{
int index = n-1;
int tmp = str[index] - ‘0‘ + 1;
int offset = 0;
while (index>0){//如果index==0则表示已经超出了最大n位数的值,返回false
tmp += offset;
if (tmp < 10){
++str[index]; return true;
}
else{
str[index] = (tmp % 10) + ‘0‘;
offset = tmp / 10;
}
--index;
tmp = str[index] - ‘0‘;
}
return false;
}
void PrintNum(char*& str,int n)
{
int i = 0;
while (str[i] == ‘0‘)
++i;
while (i < n+1){
cout << str[i];
++i;
}
cout << endl;
}
void Print1ToNdigits(int n)
{
if (n < 1)return;
char* str = new char[n + 1];
memset(str, ‘0‘, sizeof(char)*(n + 1));
while (Incerment(str,n+1)){
PrintNum(str,n);
}
delete[] str;
}《完》
本文出自 “零蛋蛋” 博客,谢绝转载!
原文:http://lingdandan.blog.51cto.com/10697032/1908548