题解 | 2的幂次方

2的幂次方

https://www.nowcoder.com/practice/7cf7b0706d7e4b439481f53e5fdac6e7

#include <iostream>
#include <string>
using namespace std;

//返回没有逆转过的二进制形式,方便solve函数利用i判断指数的实际大小。
string to_binary(int n){ 
    string res="";
    while(n!=0){
        char digit = n%2+'0';
        res += digit;
        n/=2;
    }
    return res;
    //例:如果n是11,则此处会返回"1101"而非"1011"
}

void solve(int n) {
    bool first = true; // 用于控制'+'号的输出
    string str = to_binary(n);
    for (int i = str.size()-1; i >= 0; i--) {
        if (str[i] == '1') { // 如果第i位是1,说明包含2^i
            if (!first) cout << "+";
    
            if (i==0) {
                cout << "2(0)";
            } else if (i == 1) {
                cout << "2";
            } else {
                // 指数大于1,递归处理括号内的指数i
                cout << "2(";
                solve(i); 
                cout << ")";
            }
            first = false;
        }
    }
}

int main() {
    int n;
    while (cin>>n) {
        solve(n);
        cout<<endl;
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务