1. 題目:
輸入數字n,按順序打印出從1到最大的n位十進制數,比如:輸入3,打印出:1、2、3、......、999
2. 代碼
看了[1]的解題思路,在linux環境下用c++測試了一下:
/* * Author: xiaohuan * Time: 2014-03-30 */ #include <string> #include <iostream> using std::string; using std::cout; using std::cin; using std::endl; int increment(string & str){ if(str.empty()) return -1; for(int i=str.size()-1; i>=0; --i){ if(str[i] != '9'){ str[i] += 1; break; } if(i==0){ return -1; }else{ str[i] = '0'; } } return 0; } int main(){ int NUM; cout<<"please input number:"; while(cin>>NUM){ if(NUM <= 0){ cout<<"you input one invalid number!!!"<<endl; cout<<"please input number:"; continue; } std::string numstr(NUM, '0'); while(-1 != increment(numstr)){ int pos = numstr.find_first_not_of('0'); cout<< numstr.substr(pos)<<'\t'; } cout<<endl<<"please input another number:"; } cout<<endl; return 0; }
測試如下:
linux$ ./test please input number:-1 you input one invalid number!!! please input number:0 you input one invalid number!!! please input number:1 1 2 3 4 5 6 7 8 9 please input another number:2 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 227 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 553 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 779 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 please input another number:(Ctrl+D)
3. 引用
[1]. 張海濤. 《劍指Offer:名企面試官精講典型編程題》.[M]電子工業出版社.