海涛老师的面试题-作业12-打印从1到最大的n位数

View Code
  1 // 打印从1到最大的n位数.cpp : 定义控制台应用程序的入口点。
  2 //
  3 
  4 /********************************************
  5 
  6 题目:输入数字n,按顺序打印从1到最大的n位十进制数,
  7 比如3,则打印1,2,3,一直到999;
  8  
  9 ********************************************/
 10 
 11 #include "stdafx.h"
 12 #include <string.h>
 13 #include <iostream>
 14 using namespace std;
 15 
 16 void PrintNumber(char* Number)
 17 {
 18     bool isBegin=true;
 19     int nLength=strlen(Number);
 20     for(int i=0;i<nLength;i++)
 21     {
 22         if(isBegin&&Number[i]!='0')
 23             isBegin=false;
 24         if(!isBegin)
 25             cout<<Number[i];
 26     }
 27     cout<<"\t";
 28 }
 29 
 30 bool Increment(char* Number)
 31 {
 32     bool IsOverflow=false;
 33     int  nTakeOver=0;
 34     int  nLength=strlen(Number);
 35     for(int i=nLength-1;i>=0;i--)
 36     {
 37         int nSum=Number[i]-'0'+nTakeOver;
 38         if(i==nLength-1)
 39             nSum++;
 40         if(nSum>=10)
 41         {
 42             if(i==0)
 43                 IsOverflow=true;
 44             else
 45             {
 46                 nSum-=10;
 47                 nTakeOver=1;
 48                 Number[i]=nSum+'0';
 49             }
 50         }
 51         else
 52         {
 53             Number[i]='0'+nSum;
 54             break;
 55         }
 56     }
 57     
 58         return IsOverflow;
 59 }
 60 
 61 
 62 void Print1ToMaxOfDigits(int n)
 63 {
 64     if(n<0)
 65         return;
 66     char *Number=new char[n+1];
 67     memset(Number,'0',n);
 68     Number[n]='\0';
 69     while(!Increment(Number))
 70         PrintNumber(Number);
 71     delete []Number;
 72 }
 73 
 74 
 75 
 76 
 77 void Print1ToMaxNDigitsRecur(char *Number,int Length,int index)
 78 {
 79     if(index==Length-1)
 80     {
 81             PrintNumber(Number);
 82             return;
 83     }
 84     for(int i=0;i<10;++i)
 85     {
 86         Number[index+1]=i+'0';
 87         Print1ToMaxNDigitsRecur(Number,Length,index+1);
 88     }
 89 }
 90 
 91 
 92 void Print1ToMaxtOfNDigits(int n)
 93 {
 94     if(n<=0)
 95         return;
 96     char* Number=new char[n+1];
 97     Number[n]='\0';
 98     for(int i=0;i<10;i++)
 99     {
100         Number[0]=i+'0';
101         Print1ToMaxNDigitsRecur(Number,n,0);
102     }
103 }
104 
105 int _tmain(int argc, _TCHAR* argv[])
106 {
107     //Print1ToMaxOfDigits(5);
108     Print1ToMaxtOfNDigits(5);
109     return 0;
110 }

posted on 2012-06-27 20:01  北冥茶花开  阅读(132)  评论(0编辑  收藏  举报

导航