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]电子工业出版社.