剑指Office上的一道题
打印从1到最大位数
解题思路:由于n的值未知,我们必须考虑n位数的溢出问题。在这里我们并没有使用int型的数组保存最大值,而是使用char型数组保存数值。具体代码如下:
// ConsoleApplication20.cpp : 定义控制台应用程序的入口点。
//打印从1到最大的n位数#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
void printNumber(char *a){
bool isbegin = false;
int len = strlen(a);
for (int i = 0; i < len; i++){
if (a[i] != '0')
isbegin = true;
if (isbegin){
cout << a[i];
}
}
cout << " ";
}
void PrintNumberRecursively(int n,char *a,int N){
if (n == 0)
{
printNumber(a);
return;
}
for (int i = 0; i <= 9; i++){
a[N - n] = i + '0';
//cout << a[N - n] << " ";
PrintNumberRecursively(n - 1, a, N);
}
}
void printToMaxOfDigits(int n){
char *a = new char[n + 1];
a[n] = '\0';
int N = n;
PrintNumberRecursively(n, a, N);
}
int _tmain(int argc, _TCHAR* argv[])
{
int n;
cout << "请输入n值:";
cin >> n;
printToMaxOfDigits(n);
system("pause");
return 0;
}