C++ 算法实现:将整数转换为 2 的幂次方表示
#include
string powerOf2(int n) { if (n == 0) { return "0"; } else if (n == 1) { return "2(0)"; } else if (n == 2) { return "2"; } else { string result = ""; int i = 0; while (n > 0) { if (n % 2 == 1) { string power = (i == 0) ? "0" : (i == 1) ? "" : powerOf2(i); result = "2(" + power + ")" + (result.empty() ? "" : "+") + result; } n /= 2; i++; } return result; } }
int main() { int n; cin >> n; string result = powerOf2(n); cout << result << endl; return 0; }
原文地址: https://www.cveoy.top/t/topic/o7IH 著作权归作者所有。请勿转载和采集!