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) { result = (result != "") ? "+" + result : ""; result = (i == 0) ? "2(0)" + result : (i == 1) ? "2" + result : "2(" + powerOf2(i) + ")" + 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/o7IQ 著作权归作者所有。请勿转载和采集!