2的幂次方 王道P139 练习使用 递归与分治 GOOD

//2的幂次方   王道P139 练习使用 递归与分治 GOOD
//https://www.nowcoder.com/practice/7cf7b0706d7e4b439481f53e5fdac6e7?tpId=62&tqId=29460&tPage=1&rp=1&ru=/ta/sju-kaoyan
//网上写法
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include <cmath>
using namespace std;

const int maxn = 15;//2的14次方 16384  2的15次方 32768  n<=20000
int num[maxn];

string fun(int n) {
    if (n == 0)
        return "0";
    int index = maxn - 1;
    string s="";
    while (n != 0) {
        for (; index >= 0; index--) {
            if (num[index] <= n) {
                if (index == 1)
                    s = s + "2+";
                else {
                    s = s + "2(" + fun(index) + ")+";
                }
                n -= num[index];
            }
        }
    }
    s.pop_back(); //删除源字符串的最后一个字符
    return s;
}

void init() {
    for (int i = 0; i < maxn; i++) {
        num[i] = pow(2, i);
    }
}

int main() {
    int n;
    init();
    while (cin >> n) {
        string s = fun(n);
        cout << s << endl;
    }
}

全部评论

相关推荐

2025-12-16 17:17
门头沟学院 产品经理
烤点老白薯:他第二句话的潜台词是想让你帮他点个瑞幸或者喜茶啥的
mt对你说过最有启发的一...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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