Zhi of algorithm Training 2 indicates time limit: 1.0s memory Limit: 512.0MB problem description Any positive integer can be represented in 2, for example: 137 of 2 is represented as 10001001.
This type of 2 is represented as the sum of the powers of 2, so that the power of the exponent is in the first place, and the following expression can be obtained: 137=2^7+2^3+2^0
Now the appointment power is expressed in parentheses, that is, a^b is represented as a (b).
At this point, 137 can be expressed as: 2 (7) +2 (3) +2 (0)
Further: 7=2^2+2+2^0 (2^1 with 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 finally be expressed as:
2 (2 (2+2 (0)) +2) +2 (2 (2+2 (0))) +2 (2 (2) +2 (0)) +2+2 (0 Input format positive integer (1<=n<=20000) output format conforming to the agreed N 0,2 representation (no spaces in representations) sample input 137 sample loss 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+2 (0))) +2 (2 (2) +2 (0)) +2+2 (0)
Tips
The recursive implementation will be simpler, you can output the side recursively
#include <iostream>
#include <stdio.h>
#include <memory.h>
using namespace Std;
void Cimi (int n)
{
int a[20],num=0,i=0;
while (n)
{
if (n%2)
A[num++]=i;
i++;
n/=2;
}
for (int i=num-1;i>=0;i--)
{
if (a[i]==0) printf ("2 (0)");
if (a[i]==1) printf ("2");
if (a[i]==2) printf ("2 (2)");
if (a[i]>2) {printf ("2 (");
Cimi (A[i]);
printf (")");}
if (i)
printf ("+");
}
}
int main (void)
{
int n;
while (scanf ("%d", &n)!=eof)
{
Cimi (n);
printf ("\ n");
}
return 0;
}