1.题目描述:
输入数字n,按顺序打印出从1到最大的n位十进制数。比如输入3,则打印出1、2、3一直到最大的3位数即999。
2.源代码:
// Copyright (c) 2015年 skewrain. All rights reserved.
#include <iostream>
#include <stdio.h>
using namespace std;
//跳进面试官的陷阱,没有考虑大数问题。
void Print1ToMaxOfNDigits_1(int n)
{
int number = 1;
int i = 0;
while (i++ < n) {
number *= 10;
}
for (i = 1; i < number; ++i) {
printf("%d ",i);
}
}
//绕过陷阱,在字符串上模拟数字加法的解法
bool Increment(char *number)
{
bool isOverflow = false;
int nTakeOver = 0;
int nLength = (int)strlen(number);
for (int i = nLength-1; i >= 0; i--)
{
int nSum = number[i] - '0' + nTakeOver;
if(i == nLength-1)
nSum++;
if(nSum>=10)
{
if(i==0)
isOverflow = true;
else
{
nSum -= 10;
nTakeOver = 1;
number[i] = '0'+nSum;
}
}
else
{
number[i] = '0' + nSum;
break;
}
}
return isOverflow;
}
void PrintNumber(char* number)
{
bool isBeginning0 = true;
int nLength = (int)strlen(number);
for (int i=0; i<nLength; ++i) {
if (isBeginning0 && number[i] != '0') {
isBeginning0 = false;
}
if (!isBeginning0) {
printf("%c",number[i]);
}
}
printf(" ");
}
void Print1ToMaxOfNDigits_2(int n)
{
if(n <= 0)
return;
char *number = new char[n+1];
memset(number, '0', n);
number[n] = '\0';
while (!Increment(number)) {
PrintNumber(number);
}
delete []number;
}
//把问题转换成数字排列的解法,递归让代码更简洁
void Print1ToMaxOfNDigitsRecursively(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';
Print1ToMaxOfNDigitsRecursively(number, length, index+1);
}
}
void Print1ToMaxOfNDigits_3(int n)
{
if(n <= 0)
return;
char *number = new char[n+1];
number[n] = '\0';
for (int i = 0; i<10; ++i) {
number[0]=i+'0';
Print1ToMaxOfNDigitsRecursively(number,n,0);
}
delete []number;
}
int main(int argc,char *argv[]){
int n;
cout<<"(打印从1到最大的n位数)"<<endl;
cout<<"请输入n:";
cin>>n;
cout<<"------------------------"<<endl;
Print1ToMaxOfNDigits_1(n);
cout<<endl;
cout<<"------------------------"<<endl;
Print1ToMaxOfNDigits_2(n);
cout<<endl;
cout<<"------------------------"<<endl;
Print1ToMaxOfNDigits_3(n);
cout<<endl;
return 0;
}