1 #include "stdafx.h" 2 #include <iostream> 3 #include <exception> 4 #include <vector> 5 #include <stack> 6 /* 7 题目:打印1到最大的n位数 8 输入数字n,按顺序打印出从1到最大的n位数的十进制数.比如输入3,则打印出1,2,3一直到最大的3位数即999 9 */ 10 using namespace std; 11 12 bool Increment(char * number) 13 { 14 bool isOverflow = false; 15 int nTakeOver = 0; 16 int nLength = strlen(number); 17 cout<<"strlen(number):"<<nLength<<endl; 18 for(int i = nLength -1;i>=0;--i) 19 { 20 int nSum = number[i]-‘0‘+nTakeOver;//将第i位的字符改成整形.加上是否有进位. 21 if(i==nLength-1) 22 nSum++; //往最低位加一个1,如果加上1,大于等于10.就要往前进位. 23 if(nSum>=10) 24 { 25 if(i==0) 26 isOverflow = true; 27 else 28 { 29 nSum -=10; 30 nTakeOver = 1; 31 number[i] = ‘0‘ +nSum; 32 } 33 } 34 else 35 { 36 number[i] = ‘0‘ +nSum; 37 break; 38 } 39 } 40 return isOverflow; 41 } 42 void PrintNumber(char* number) 43 { 44 while(*number==‘0‘) 45 number++; 46 cout<<number<<endl; 47 } 48 49 50 int _tmain(int argc, _TCHAR* argv[]) 51 { 52 int n; 53 cin>>n; 54 if(n<=0) 55 56 { 57 cout<<"n不合适"<<endl; 58 } 59 else 60 { 61 char *number = new char[n+1]; 62 //number[0]=‘0‘; 63 memset(number,‘0‘,n); 64 number[n] = ‘\0‘; 65 while(!Increment(number)) 66 { 67 PrintNumber(number); 68 } 69 delete []number; 70 } 71 72 return 0 ; 73 }
原文:http://www.cnblogs.com/crazycodehzp/p/3561542.html