剑指offer——面试题17:打印从1到最大的n位数
用字符串模拟加法:
1 #include"iostream" 2 #include"string.h" 3 using namespace std; 4 5 bool AddOne(char *number,int n); 6 void PrintNumber(char *number,int n); 7 8 void Print1ToN(int n) 9 { 10 if(n<=0) 11 return; 12 char *number=new char[n+1]; 13 memset(number,'0',n); 14 number[n]='\0'; 15 while(AddOne(number,n)) 16 { 17 PrintNumber(number,n); 18 } 19 delete[] number; 20 } 21 22 bool AddOne(char *number,int n) 23 { 24 bool isInRange=true; 25 int carry=0; 26 int iDigit; 27 for(int i=n-1;i>=0;i--) 28 { 29 iDigit=number[i]-'0'+carry; 30 if(i==n-1) 31 iDigit++; 32 if(iDigit>=10) 33 { 34 if(i==0) 35 isInRange=false; 36 else 37 { 38 carry=iDigit/10; 39 iDigit%=10; 40 number[i]=iDigit+'0'; 41 } 42 } 43 else 44 { 45 number[i]=iDigit+'0'; 46 break; 47 } 48 } 49 return isInRange; 50 } 51 52 void PrintNumber(char *number,int n) 53 { 54 bool firstNoZero=false; 55 for(int i=0;i<n;i++) 56 { 57 if(!firstNoZero&&number[i]!='0') 58 { 59 firstNoZero=true; 60 } 61 if(firstNoZero) 62 cout<<number[i]; 63 } 64 cout<<endl; 65 } 66 int main() 67 { 68 int n; 69 while(cin>>n) 70 { 71 Print1ToN(n); 72 } 73 return 0; 74 }
还可以用全排列的思想,递归调用去解决:
1 #include"iostream" 2 using namespace std; 3 4 void Print1ToNRecursively(int *number,int length,int index); 5 void PrintNumber(int *number,int n); 6 7 void Print1ToN(int n) 8 { 9 int *number=new int[n]; 10 11 for(int i=0;i<10;i++) 12 { 13 number[0]=i; 14 Print1ToNRecursively(number,n,0); 15 } 16 } 17 18 void Print1ToNRecursively(int *number,int length,int index) 19 { 20 if(index==length-1) 21 { 22 PrintNumber(number,length); 23 return; 24 } 25 for(int i=0;i<10;i++) 26 { 27 number[index+1]=i; 28 Print1ToNRecursively(number,length,index+1); 29 } 30 } 31 32 void PrintNumber(int *number,int n) 33 { 34 int i=-1; 35 while(i<n&&number[++i]==0) continue; 36 while(i<n) cout<<number[i++]; 37 cout<<endl; 38 } 39 40 int main() 41 { 42 int n; 43 while(cin>>n) 44 { 45 Print1ToN(n); 46 } 47 return 0; 48 }