题解 | 2的幂次方
2的幂次方
https://www.nowcoder.com/practice/7cf7b0706d7e4b439481f53e5fdac6e7
#include <iostream>
#include <cstring>
#include <algorithm>
#include<vector>
#include<string>
using namespace std;
//直接递归的输出结果
//string dfs(int n) {
// string res;
// int count = 0;
// while (n > 0) {
// if (n & 1) {
// if (res.size())res += "+";//不是第一个元素的话,前面有加号
// if (count == 0)res += "2(0)";
// else if (count == 1)res += "2";
// else {
// res += "2(" + dfs(count) + ")";
// }
//
// }
// n >>= 1;
// count++;
// }
// return res;
//}
//但是由于本题是要从高位到低位,所以要倒着输出
string dfs(int n) {
string res;
//本题最大也就是20000,所以最多也就是2^15
for (int i = 14; i >= 0; i--) {
//若这位是1则要进行展开
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 n;
while (cin >> n) {
cout << dfs(n) << endl;
}
}
查看17道真题和解析