牛客网 递归输出2次幂

题目描述

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
  1. 常用的<<和>>方法:
    (n >> i)&1 //加入右移i位后,n不为零,则符合条件
    (1 << i)&n //判断整数n的第i位是否为1
  2. 符号常量和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)使用初拉力
  3. 大于等于 是“>=”

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值