秋逸

题目描述

任何一个正整数都可以用 2 的幂次方表示。

例如:

137 = 2^7 + 2^3 + 2^0

同时约定次方用括号来表示,即 ab 可表示为 a(b)。

由此可知,137 可表示为:

2(7)+2(3)+2(0)

进一步:7 = 2^2 + 2 + 2^0(21 用 2 表示)

3=2+2^0

所以最后 137 可表示为:

2(2(2)+2+2(0))+2(2+2(0))+2(0)

又如:

1315=2^10 +2^8 +2^5 +2+1

所以 1315 最后可表示为:

 2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)

输入

每个测试文件只包含一组测试数据,每组输入一个正整数 n(n<=20000)。

输出

对于每组输入数据,输出符合约定的 n 的 0,2 表示。(在表示中不能有空格)

样例输入

137

样例输出

2(2(2)+2+2(0))+2(2+2(0))+2(0)

思路

一看就要递归,然后拿张纸自己算了算,大概知道了拆解过程,便计算边输出,不需要返回值,因此定义一个void d(int n) d函数得到一个整数n,先判断是否需要继续拆解。

pow(x,y)是C语言函数,返回x^y,类型为double

我的代码

#include <bits/stdc++.h>

using namespace std;

void d(int n){
    if(n==1){
        cout<<"2(0)";
    }else if(n==2){
        cout<<"2";
    }else{
        int i,s=0;
        for(i=1;n-pow(2,i)>0;i++);
        int res=n-pow(2,i);
        if(res<0){
            i--;
            res=n-pow(2,i);
        }
        if(i>1){
            cout<<"2(";
            d(i);
            cout<<")";
        }else{
                cout<<"2";
        }
        if(res!=0){
            cout<<"+";
            d(res);
        }
    }
    return;
}

int main(){
    int n;
    cin>>n;
    d(n);
    return 0;
}
二的幂次方-题解
: 杨秋逸
https://yangqiuyi.com/blog/算法/二的幂次方-题解/
© 2025 杨秋逸 . All rights reserved.