1501102328-Sub-power expression of Blue Bridge cup-algorithm training 2
Algorithm training 2 power expression time limit: 1.0 s memory limit: 512.0 MBProblem description any positive integer can be expressed in binary notation. For example, the binary notation of 137 is 10001001.
This binary representation is written as the sum of the power of the second, so that the power of the second is ranked first. The following expression can be obtained: 137 = 2 ^ 7 + 2 ^ 3 + 2 ^ 0
The power is represented by parentheses, that is, a ^ B is represented as a (B)
In this case, 137 can be expressed as: 2 (7) + 2 (3) + 2 (0)
Further: 7 = 2 ^ 2 + 2 + 2 ^ 0 (2 ^ 1 is expressed as 2)
3 = 2 + 2 ^ 0
So the last 137 can be expressed as: 2 (2 (2) + 2 + 2 (0) + 2 (2 + 2 (0) + 2 (0)
Another example: 1315 = 2 ^ 10 + 2 ^ 8 + 2 ^ 5 + 2 + 1
So 1315 can be expressed:
2 (2 (2 + 2 (0) + 2) + 2 (2 (2 + 2 (0) + 2 (2 (2) + 2 (0 )) + 2 + 2 (0) positive integer in the input format (1 <= n <= 20000) the output format conforms to the agreed 0, 2 Representation of n (the representation cannot contain spaces) example input 137 sample output 2 (2 (2) + 2 + 2 (0) + 2 (2 + 2 (0) + 2 (0) sample input 1315 sample output 2 (2 (2 + 2 (0) + 2) + 2 (2 + 2 (0 ))) + 2 (2 (2) + 2 (0) + 2 + 2 (0)
Prompt
Recursive Implementation is relatively simple. It can be implemented by recursion while outputting the solution ideas. Convert the decimal number into a binary number. The number of cycles in the conversion process is 1, and then judge. The recursive boundary is when n = 0, n = 1n = 2. However, it should be noted that you must determine when the + number is output and when it is not. When not the last one, the output + array should be defined as a local variable, because each array is stored differently. Code
# Include
Int main () {int n; void cimi (int n); while (scanf ("% d", & n )! = EOF) {cimi (n); printf ("\ n") ;}return 0 ;}void cimi (int n) {int num; int I, j, k; int a [32]; // The array is defined as the local variable num = 0; I = 0; while (n) {j = n % 2; if (j = 1) a [num ++] = I; // The number of storage times is 1 I ++; n/= 2;} for (I = num-1; I> = 0; I --) {if (a [I] = 0) printf ("2 (0)"); else if (a [I] = 1) printf ("2"); else if (a [I] = 2) printf ("2 (2)"); else if (a [I]> 2) {printf ("2 ("); cimi (a [I]); printf (")");} if (I! = 0) printf ("+"); // output if not the last one + }}