描述
任何一个正整数都可以用2的幂次方表示。例如:
137=27+23+20
同时约定方次用括号来表示,即ab可表示为a(b)。由此可知,137可表示为:
2(7)+2(3)+2(0)
进一步:7=22+2+20(21用2表示)
3=2+20
所以最后137可表示为:
2(2(2)+2+2(0))+2(2+2(0))+2(0)
又如:
1315=210+28+25+2+1
所以1315最后可表示为:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
输入
一个正整数n(n≤20000)。
输出
一行,符合约定的n的0,2表示(在表示中不能有空格)。
样例输入
137样例输出
2(2(2)+2+2(0))+2(2+2(0))+2(0)
递归:先利用移位运算符得到二进制下的该数的各个位,然后对每个幂次大于1的位对其幂次进行本处理。
P.S. 本题的输出格式搞了好久
#include <iostream>
using namespace std;
bool GetBit(int x, int i) //返回x的第i位
{
return (x >> i) & 1;
}
void func(int x)
{
//统计最大是多少位
int temp = x;
int cnt = -1;
while (temp)
{
temp >>= 1;
cnt++;
}
for (int i = cnt; i >= 0; i--)
{
int bit = GetBit(x, i);
if (bit)
{
if (i != cnt)
cout << "+";
if (i == 1)
cout << "2";
else if (i == 0)
cout << "2(0)";
else
{
cout << "2(";
func(i);
cout << ")";
}
}
}
}
int main()
{
int x;
cin >> x;
func(x);
}