打印1到最大的n位数*

注意:需考虑大数问题

方法一:

void PrintFrom1ToMax(int n)
{
	if (n <= 0)
		return;

	char* arrPrintStr = new char[n+1];
	memset(arrPrintStr, '0', n);
	arrPrintStr[n] = '\0';
	while (!Increment(arrPrintStr))
	{
		PrintNumber(arrPrintStr);
	}
	delete []arrPrintStr;
}

bool Increment(char* arrNumber)
{
	bool bIsOverflow = false;
	int nTakeOver = 0;
	int nLength = strlen(arrNumber);
	for (int i = nLength - 1; i >= 0; i--)
	{
		int num = arrNumber[i] - '0' + nTakeOver;
		if (i == nLength - 1)
			num++;

		if (num >= 10)
		{
			if (i == 0)
				bIsOverflow = true;
			else
			{
				num -= 10;
				nTakeOver = 1;
				arrNumber[i] = '0' + num;
			}
		}
		else
		{
			arrNumber[i] = '0' + num;
			break;
		}
	}
	return bIsOverflow;
}

void PrintNumber(char* arrNumber)
{
	bool bStartPrint = false;
	int nLength = strlen(arrNumber);
	for (int i = 0; i < nLength; ++i)
	{
		if (!bStartPrint && arrNumber[i] != '0')
			bStartPrint = true;
		if (bStartPrint)
			printf("%c", arrNumber[i]);
	}
}

  

方法二(递归):

void PrintFrom1ToMax(int n)
{
	if (n <= 0)
		return;
	char* arrNumber = new char[n + 1];
	arrNumber[n] = '\0';

	for (int i = 0; i < 10; ++i)
	{
		arrNumber[0] = i + '0';
		PrintFrom1ToMaxRecursively(arrNumber, n, 0);
	}
	delete []arrNumber;
}
void PrintFrom1ToMaxRecursively(char* arrNumber, int length, int index)
{
	if (index == length - 1)
	{
		PrintNumber(arrNumber);
		return;
	}
	for (int i = 0; i < 10; ++i)
	{
		arrNumber[index + 1] = i + '0';
		PrintFrom1ToMaxRecursively(arrNumber, length, index + 1);
	}
}

  

  

posted on 2021-02-08 15:32  Noora&w  阅读(93)  评论(0编辑  收藏  举报