面试题12:打印1到最大的n位数(大数问题)
面试题是关于n位整数并且没有限定n的取值范围,或者是输入任意大小的整数,那么这个题目就很可能需要考虑大数问题。字符串是一个简单的、有效的表示大数的方法
这题比较难,用递归表达全排列,数字每一位都可能是0-9,从高位往低位设置
1 void Print1ToMaxOfNDigits_2(int n) 2 { 3 if(n <= 0) 4 return; 5 6 char* number = new char[n + 1]; 7 number[n] = '\0'; 8 9 for(int i = 0; i < 10; ++i) 10 { 11 number[0] = i + '0'; 12 Print1ToMaxOfNDigitsRecursively(number, n, 0); 13 } 14 15 delete[] number; 16 } 17 18 void Print1ToMaxOfNDigitsRecursively(char* number, int length, int index) 19 { 20 if(index == length - 1) 21 { 22 PrintNumber(number); 23 return; 24 } 25 26 for(int i = 0; i < 10; ++i) 27 { 28 number[index + 1] = i + '0'; 29 Print1ToMaxOfNDigitsRecursively(number, length, index + 1); 30 } 31 } 32 33 // 字符串number表示一个数字,数字有若干个0开头 34 // 打印出这个数字,并忽略开头的0 35 void PrintNumber(char* number) 36 { 37 bool isBeginning0 = true; 38 int nLength = strlen(number); 39 40 for(int i = 0; i < nLength; ++ i) 41 { 42 if(isBeginning0 && number[i] != '0') 43 isBeginning0 = false; 44 45 if(!isBeginning0) 46 { 47 printf("%c", number[i]); 48 } 49 } 50 51 printf("\t"); 52 }