题目描述
Every positive number can be presented by the exponential form.For example, 137 = 2^7 + 2^3 + 2^0。 Let’s present a^b by the form a(b).Then 137 is presented by 2(7)+2(3)+2(0). Since 7 = 2^2 + 2 + 2^0 and 3 = 2 + 2^0 , 137 is finally presented by 2(2(2)+2 +2(0))+2(2+2(0))+2(0). Given a positive number n,your task is to present n with the exponential form which only contains the digits 0 and 2.
输入描述:
For each case, the input file contains a positive integer n (n<=20000).
输出描述:
For each case, you should output the exponential form of n an a single line.Note that,there should not be any additional white spaces in the line.
示例1
输入
1315
输出
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
经验总结
1.六种位运算符
a<< x | 左移 | 整数a按照二进制位左移x位 |
---|---|---|
a>>x | 右移 | 整数a按照二进制位右移x位 |
a&b | 位与 | a和b按照二进制位对齐,按位进行与运算 (11得1,其余为0) |
| | 位或 | a和b按照二进制位对齐,按位进行与运算 (00得0,其余为1) |
^ | 异或 | 按照二进制对齐,相同为1,不同为0 |
- 常用的<<和>>方法:
(n >> i)&1 //加入右移i位后,n不为零,则符合条件
(1 << i)&n //判断整数n的第i位是否为1 - 符号常量和const常量
#define pi 3.14 //将pi的值定位3.14,同时pi的值不能再改变
const double pi=3.14 //将pi的值定位3.14,同时pi的值不能再改变
#define add(a,b) ((a)+(b)) //将a+b这个式子用add(a,b)使用初拉力 - 大于等于 是“>=”
AC代码
#include<iostream>
#include<string>
using namespace std;
string dfs(int n){
string s;
if(n == 2){return "2";}
if(n == 0){return "0";} //递归出口
int i = 20;
while (i--)
{
if((n >> i)&1){
if(i == 1){s +="2+";} //当值为2时,2后面是没有括号的,要特殊化
else
{
s += "2(";
s += dfs(i); //递归
s += ")";
s += "+";
}
}
}
s = s.substr(0,s.size()-1); //按照程序,最后会有一个加号,因此在此处输出s的子串,将+消除
return s;
}
int main() {
int n;
string r;
while (cin >> n) {
r = dfs(n); //递归
cout << r << endl;
}
return 0;
}