注:之前写了使用大数打印的方法
C#代码
#region 打印1到最大的n位数
/// <summary>
/// 输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1、2、3一直到最大的3位数即999。
/// 使用递归算法实现,以及使用字符排列的方式,如对000~999进行全排列。
/// </summary>
class MaxOfDigital
{
private int _n;
public int n
{
get { return _n; }
set { _n = value; }
}
public MaxOfDigital(int n)
{ _n = n; }
public void PrintToMaxOfDigits()
{
if (n <= 0)
{
Console.WriteLine("n的值必须大于0!");
return;
}
List<char> number = new List<char>();
for (int i = 0; i < n; i++) number.Add('0');
for (int i = 0; i < 10; i++)
{
number[0] = Convert.ToChar(48+i);
PrintToMaxOfDigitsRecursiverly(number, n, 0);
}
}
private void PrintToMaxOfDigitsRecursiverly(List<char> number,int length,int index)
{
if (index == length - 1)
{
PrintNumber(number);
return;
}
for (int i = 0; i < 10; i++)
{
number[index + 1] = Convert.ToChar(48+i);
PrintToMaxOfDigitsRecursiverly(number, length, index + 1);
}
}
public void PrintNumber(List<char> number)
{
number.ForEach(
delegate(char num)
{
bool isBeginning0 = false;
if (num == '0' && isBeginning0 == false)
{
isBeginning0 = true;
}
else
Console.Write(num);
}
);
Console.Write(" ");
}
}
#endregion
C++代码
以下是《剑指Offer》的代码,printNumber函数简化了,
void PrintToMaxOfDigital(int n)
{
if(n<=0)
return;
char *num = new char[n+1];
num[n]='\0';
for(int i =0 ;i<10;i++)
{
num[0]= i+'0';
PrintToMaxOfDigitalsRescursively(num,n,0);
}
delete []num;
}
void printNumber(char *num)
{
copy(num,num+strlen(num),ostream_iterator<char,char>(cout,""));
cout<<",";
}
void PrintToMaxOfDigitalsRescursively(char *num,int length,int index)
{
if(index == length)
{
printNumber(num);
return;
}
for(int i=0;i<10;i++)
{
num[index+1]= i+'0';
PrintToMaxOfDigitalsRescursively(num,length,index+1);
}
}
对以上函数进行了简化、
void PrintToMaxOfDigital(int n)
{
if(n<=0)
return;
char *num = new char[n+1];
num[n]='\0';
PrintToMaxOfDigitalsRescursively(num,n,0);
delete []num;
}
void printNumber(char *num)
{
copy(num,num+strlen(num),ostream_iterator<char,char>(cout,""));
cout<<",";
}
void PrintToMaxOfDigitalsRescursively(char *num,int length,int index)
{
if(index == length)
{
printNumber(num);
return;
}
for(int i=0;i<10;i++)
{
num[index]= i+'0';
PrintToMaxOfDigitalsRescursively(num,length,index+1);
}
}