C++ 正整数二进制表示转换算法实现
#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) { if (result != "") { result = "+" + result; } if (i == 0) { result = "2(0)" + result; } else if (i == 1) { result = "2" + result; } else { result = "2(" + powerOf2(i) + ")" + result; } } n = 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/o7Iy 著作权归作者所有。请勿转载和采集!