剑指offer:打印1到最大的n位数

来源:互联网 发布:天猫关键词优化 编辑:程序博客网 时间:2024/05/22 17:25

我没有按照剑指offer书上给的思路,自己写了一种实现方式:

#include <iostream>#include <vector>#include <algorithm>using namespace std;void printIncreaseNum(const int n){char* pdata = NULL ;int i = 0 , count = 0;int wei = 0;int len = 0 , j = 0;if(0 == n){return;}/* 分配内存 */pdata = new char[n+1];for(i = 0; i < n+1; i++){pdata[i] = '0';}i = 0;while(1){/* 进位标识 */wei = 0;/* 如果现在不需要进位 */if(i < 9){pdata[0] += 1; i++;}/* 需要进位 */else{i = 0;wei++;while(1){/* 判断是否位数增加 */if(pdata[wei] == '\0'){count++;pdata[wei] = '0';}if(pdata[wei] != '9'){pdata[wei] = pdata[wei] + 1;break;}else{wei++;}}}/* 判断有没有进位,有进位之后把后面的几项置0 */if(wei != 0){wei --;while(wei >= 0){pdata[wei] = '0';wei--;}}/* 给字符串加上结束符 */pdata[count+1] = '\0';/* 循环结束 */if(count == n){break;}/* 打印出该数据 */len = strlen(pdata);for(j = len-1; j >= 0; j--){cout << pdata[j];}cout << endl;}}int main(){int n = 0;cin >> n;printIncreaseNum(n);return 0;}


0 0
原创粉丝点击