weinan030416

导航

dfs:2的幂次方表示数字

#include<iostream>
#include<vector>
#include<bitset>
#include<string>
#include<algorithm>
using namespace std;

vector<string> res;
void dfs(int x)
{
    bitset<16>    a(x);//转换为2进制 ,根据题目给的最大数设置bitset位数 
    bool isfirstone=true;
    for(int i=15;i>=0;--i)
    {
        if(a.test(i))//第i位置是1 
        {
            if(!isfirstone)//不是第一个数 
            {
                res.push_back("+");
            }
            else
                isfirstone=false;
            if(i==0)
                res.push_back("2(0)");//除了1和2直接写上,其他要转换 
            else if(i==1)
                res.push_back("2");
            else
            {
                res.push_back("2(");//例子:把2的7次方这种变为2(2(2)+2+2(0)) 4+2+1
                dfs(i);
                res.push_back(")");
            }
        }
    }
    return; 
}
int main()
{
    int x;
    cin>>x;
    dfs(x);
    for(vector<string>::iterator m=res.begin();m!=res.end();m++)
    {
        cout<<*m;
    }
 }

 

posted on 2023-01-18 13:09  楠030416  阅读(12)  评论(0编辑  收藏  举报