题解 | #2的幂次方#
2的幂次方
https://www.nowcoder.com/practice/7cf7b0706d7e4b439481f53e5fdac6e7
递归思想要好好消化,先得出非零的幂,然后按幂从高到低组字符串
#include <iostream> #include "vector" using namespace std; vector<int> getExponential(int n) { vector<int> ans; int exp = 0; while (n != 0) { if (n % 2 == 1) ans.push_back(exp); n /= 2; exp++; } return ans; } string present(int n) { vector<int> exps = getExponential(n); string ans; for (int i = exps.size()-1; i >=0; i--) { int item = exps[i]; if (item == 0)ans += "2(0)"; else if (item == 1) ans += "2"; else if (item == 2) ans += "2(2)"; else { ans += "2(" + present(item) + ")"; } if (i != 0) ans += "+"; } return ans; } int main() { int n; while (cin >> n) { // 注意 while 处理多个 case cout <<present(n) << endl; } } // 64 位输出请用 printf("%lld")