Power representation of 2
Problem description
Any positive integer can be expressed in binary, for example, the binary of 137 is 10001001.
This binary representation is written in the form of the sum of the powers of 2, so that the higher of the powers comes first, and the following expression can be obtained: 137 = 27 ^ 77 + 23 ^ 33 + 20 ^ 00
Now, the power is expressed in parentheses, that is, a^b is expressed as a (b)
In this case, 137 can be expressed as: 2 (7) + 2 (3) + 2 (0)
Further: 7 = 22 ^ 22 + 2 + 20 ^ 00 (2 ^ 1 is represented by 2)
3=2+20^00
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 + 28 ^ 88 + 25 ^ 55 + 2 + 1
So 1315 can 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
0, 2 of n according to the Convention (no space in the representation)
sample 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+2(0)))+2(2(2)+2(0))+2+2(0)
Tips
It's easy to implement with recursion. You can output at the same time of recursion
#include <iostream> using namespace std; void func(int a); int main(){ int n; cin >> n; func(n); return 0; } void func(int a){ int i = 0; int s[100] = {0}; if(a == 0) { cout << ""; } else { while (a != 0) { s[i++] = a % 2; a = a / 2; } //137 10001001 i = 8,i - 1 = 7 int t = 0;//7 111 i=3, i - 1 =2 for (int c = 0; c <= i - 1; c++){ if (s[c] == 1){ t = c; // t = 0 break; } } //j = 2,t+1 = 1 j= 7,t+1 = 1 for (int j = i - 1; j >= t + 1; j--) { if (s[j] != 0) { if (j == 1) { cout << "2+"; } else if (j == 2) { cout << "2(2)+"; }//① else { cout << "2("; func (j);// cout << ")+"; } } } if (t == 0) { cout << "2(0)"; } else if (t == 1) { cout << "2"; } else if (t == 2) { cout << "2(2)"; } else { cout << "2("; func(t); cout << ")"; } } }