您的位置:首页 > 其它

输入数字n,按顺序输出从1最大的n位10进制数

2013-03-17 22:36 465 查看
当我们求最大的n位数的时候,是不是有可能用整型甚至长整型都会溢出?分析到这里,我们很自然的就想到我们需要表达一个大数,最常用的也是最容易实现的表达大数的方法是用字符串或者整型数组(当然不一定是最有效的)。 采用类似―n位k进制枚举‖的算法(也类似于《编程之美》―电话号码对应英文单词‖),代码如下:



#include <iostream>
using namespace std;
const unsigned MaxBit = 10;
static unsigned outArr[MaxBit];
const char *HighBit = "123456789";
const unsigned HighNum = 10;
const char *OtherBit = "0123456789";
const unsigned OtherNum = 11;

void PrintAllNumberWithNBits(unsigned int N)
{  //输出位数为N位的数,即:10^(N-1)...10^N-1
	if (N < 1) return;

	for (unsigned i = MaxBit-N; i < MaxBit; i++)
		if (i == MaxBit-1)
			outArr[i] = 0;
		else
			outArr[i] = 1;

	while (1)
	{
		int k = N;
		outArr[MaxBit-1]++;

		if(k==1 && outArr[MaxBit-1]>=HighNum)
			return; //前一个数字所有位均为9,循环结束
		else if (outArr[MaxBit-1-N+k] >= OtherNum) {
			int j = k;
			while (j>1 && outArr[MaxBit-1-N+j]>=OtherNum) {
				outArr[MaxBit-1-N+j] = 1;
				j--;
				outArr[MaxBit-1-N+j]++;
			}
			if (j==1 && outArr[MaxBit-1-N+j]>=HighNum)
				return;
		}

		for (unsigned int i = MaxBit-N; i < MaxBit; i++) {
			if (i == MaxBit-N)
				cout << HighBit[outArr[i]-1];
			else
				cout << OtherBit[outArr[i]-1];
		}
		cout << endl;
	}
}

int main()
{
	unsigned number = 0;
	cin >> number;

	for (unsigned i = 0; i < MaxBit; i++)
		outArr[i] = 0;

	// 依次输出位数为1,2,3...n-1位的数
	for (unsigned i = 1; i <= number; i++)
		PrintAllNumberWithNBits(i);

	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐