AcWing 3483. 2的幂次方
原题链接
中等
作者:
王杜杜
,
2025-01-17 17:59:01
,
所有人可见
,
阅读 1
算法1
打表
C++ 代码
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
void method1(int n){
string s[30] = {
"2(0)", //1
"2", //2
"2(2)", //4
"2(2+2(0))", //8
"2(2(2))", //16
"2(2(2)+2(0))", //32
"2(2(2)+2)", //64
"2(2(2)+2+2(0))", //128
"2(2(2+2(0)))", //256
"2(2(2+2(0))+2(0))", //512
"2(2(2+2(0))+2)", //1024
"2(2(2+2(0))+2+2(0))", //2048
"2(2(2+2(0))+2(2))", //4096
"2(2(2+2(0))+2(2)+2(0))", //8192
"2(2(2+2(0))+2(2)+2)" //16384
};
string ans;
for(int i = 15; i >=0; --i){
if((n >> i) & 1){
if(ans.size())
ans += "+";
ans += s[i];
}
}
cout << ans << endl;
}
int main()
{
int num;
while(cin >> num){
method1(num);
}
return 0;
}
算法2
递归
C++ 代码
#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
string dfs(int n){
string res;
for(int i = 14; i >= 0; i--){
if((n>>i)&1){
if(res.size()) res += "+";
if(i == 0) res += "2(0)";
else if(i == 1) res += "2";
else res += "2(" + dfs(i) + ")";
}
}
return res;
}
int main()
{
int num;
while(cin >> num){
cout << dfs(num) << endl;
}
return 0;
}