剑指offer-面试题12:打印1到最大的n位数

题目:输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1、2、3一直到最大的3位数即999.

解法:这道提的陷进在于没有规定最大的n位数的范围,会不会溢出,也就是说我们要考虑大数问题。最常用也是最容易的方法是用字符串或者数组去表达大数。

bool increment(char* number)
{
	bool IsOverFlow = false;
	int TakeOver = 0;
	int length = strlen(number);
	
	for(int index = length - 1; index >= 0; --index)
	{
		int num = number[index] - '0' + TakeOver;
		if(index == length - 1)
			++num;
		
		if(num >= 10)
		{
			if(index == 0)
				IsOverFlow = true;
			else
			{
				num -= 10;
				TakeOver = 1;
				number[index] = '0' + num;
			}
		}
		else
		{
			number[index] = '0' + num;
			break;
		}
	}
	return IsOverFlow;
}

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

void Print1ToMaxN(int n)
{
	if(n <= 0)
		return;
	char* number = new char[n+1];
	memset(number, '0', n);
	number[n] = '\0';
	while(!increment(number))
	{
		PrintNumber(number);
		cout << " " ;
	}
	cout << endl;
	delete[] number;
}

递归解法:

void PrintToMaxOfDigits
{
    if(n <= 0)
        return;
    char* number = new char[n + 1];
    number[n] = '\0';
    
    for(int i = 0; i < 10; ++i)
    {
        number[0] = i + '0';
        PrintToMaxOfDigitsRecursively(number, n, 0);
    }
    delete[] number;
}

void PrintToMaxOfDigitsRecursively(char* number, int length, int index)
{
    if(index == length - 1)
    {
        PrintNumber(number);
        return;
    }

    for(int i = 0; i < 10; ++i)
    {
        number[index + 1] = i + '0';
        PrintToMaxOfDigitsRecursively(number, length, index + 1);
    }
}



你可能感兴趣的:(剑指offer-面试题12:打印1到最大的n位数)