面试题:输入数值n,打印从1到最大的n位数,例如输入n=3,则从1,2,3,一直打印到999
该题会考查大整数的加法,我之前做大整数运算时,为了图方便,用整数数组来表示,但这会浪费空间,这次我用字符数组来表示,并且存数的时候是按正常顺序来存取
在判断是否到达上限时,通过判断最高位是否需要做进位运算来判断,具体代码如下:
#include <iostream> #include <string.h> #include <fstream> #include <stack> #include <exception> using namespace std; void print(char *num,int n) { bool shouldStart=false; for(int index=0;index<n;index++) { if(!shouldStart && num[index]!='0') { shouldStart=true; } if(shouldStart) { cout<<num[index]; } } cout<<endl; } bool incNum(char *num,int n) { bool overFlow=false; int carryBit=0; for(int index=n-1;index>=0;index--) { int sum=num[index]-'0'+carryBit; if(index==n-1) { sum++; } if(sum>=10) { if(index==0) { overFlow=true; }else { sum=sum%10; carryBit=1; num[index]=sum+'0'; } }else { carryBit=0; num[index]=sum+'0'; break; } } return overFlow; } void printAllNum(int n) { if(n<=0) { //throw new exception("the input is error"); } char *num=new char[n+1]; memset(num, '0', n); num[n]=' '; while(!incNum(num,n)) { print(num,n); } delete []num; } int main() { int n; cin>>n; printAllNum(n); //getchar(); return 0; }
第二种解法
n位数相当于对做个全排列,在输出时,把前导的0去掉,就会输出正确结果
#include <iostream> #include <string.h> #include <fstream> //#include <stack> //#include <exception> using namespace std; void printFinal(char *num,int n) { bool shouldStart=false; for(int index=0;index<n;index++) { if(!shouldStart && num[index]!='0') { shouldStart=true; } if(shouldStart) { cout<<num[index]; } } if(shouldStart) { cout<<endl; } } void print(char *num, int n,int start) { if(start==n) { printFinal(num,n); return; } for(int val=0;val<10;val++) { num[start]=val+'0'; print(num,n,start+1); } } void printAllNum(int n) { if(n<=0) { //throw new exception("the input is error"); } char *num=new char[n+1]; memset(num, '0', n); num[n]=' '; print(num,n,0); } int main() { int n; cin>>n; printAllNum(n); //getchar(); return 0; }