Subject description:
Enter the number n, the maximum print from 1 to n-bit decimal order. For example, input 3, then print out up to a maximum of 1, 2, 3 digits 999.
Analysis: Note that can not directly enter the maximum n-bit decimal number, as may belong to a large number, this number can not therefore need to represent a string or a long long int storage.
Ideas: we are all aligned solution with n bits, each bit can be a number from 0 to 9. Recursive solution. Note that the leading 0 Do not output, such as a print only when the 1-9, 1-9 2 when printing (instead of 01, ...), 10-99.
1 #include <iostream> 2 #include <algorithm> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 void Print1ToMaxOfNDigitsRecursively(char* number, int length, int index); 7 8 void PrintNumber(char* number) { 9 int index = 0; 10 bool isBeginning0 = true; 11 int nlength = strlen(number); 12 // index to the left of the first index is not zero. Of particular note is the entire string are all zero 13 is for ( int I = 0 ; I <nlength; I ++ ) { 14 IF (! Number [I] = ' 0 ' ) { 15 index = I; 16 BREAK ; . 17 } 18 is } . 19 IF ((index ==! 0 && Number [index] == ' 0 ' {)) 20 is for ( int I = index; I <nlength; I ++ ) { 21 is the printf ("%c", number[i]); 22 } 23 printf("\n"); 24 } 25 } 26 27 void Print1ToMaxOfNDigits(int n) { 28 if (n <= 0) { 29 return; 30 } 31 char *number = new char[n + 1]; 32 number[n] = '\0'; 33 for (int i = 0; i < 10; i++) { 34 number[0] = i + '0'; 35 Print1ToMaxOfNDigitsRecursively(number, n, 0); 36 } 37 delete [] number; 38 } 39 40 void Print1ToMaxOfNDigitsRecursively(char* number, int length, int index) { 41 if (index == length - 1) { 42 PrintNumber(number); 43 return; 44 } 45 for (int i = 0; i < 10; i++) { 46 number[index + 1] = i + '0'; 47 Print1ToMaxOfNDigitsRecursively(number, length, index + 1); 48 } 49 } 50 51 int main() { 52 int number; 53 while (cin >> number) { 54 Print1ToMaxOfNDigits(number); 55 } 56 return 0; 57 }