3483. 2的幂次方(递归)

题目如下:

AC代码:

#include<iostream>
#include<algorithm>
using namespace std;
string d(int n) {
    int a = 0;
    string res = "";
    while (n > 0) {
        if (1 & n) {
            if (a == 0)
                res = "2(0)";
            else if (a == 1) {
                if (res != "")
                    res = "2+" + res;
                else
                    res = "2";
            }
            else {
                string temp = d(a);
                if (res != "")
                    res = "2(" + temp + ")+" + res;
                else
                    res = "2(" + temp + ")";
            }

        }
        a += 1;
        n /= 2;
    }
    return res;
}

int main() {
    std::ios::sync_with_stdio(false);
    int n;
    while (cin >> n) {
        string r = d(n);
        cout << r << endl;
    }
    return 0;
}

        (个人喜欢在递归函数开始前写递归结束语句,但本题参数n在主函数的意义和在函数内调用的意义有所不同,递归函数中传入是幂指数,递归调用是拆解的数字,故只能在while中用if结束调用,写的很不舒服~~)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值