难点在于字符串实现加法和乘除
#include <iostream> #include <vector> using namespace std; string divide(string str) { int remain = 0; string result; for (int i = 0; i < str.size(); i++) { int temp = remain * 10 + str[i] - '0'; remain = temp % 2; char tempChar = (temp / 2 + '0'); result += tempChar; } if (result == "0") return ""; else { int pos = 0; while (result[pos] == '0') pos++; return result.substr(pos); } } string multiple(string str) { string result; int carry = 0; for (int i = str.size() - 1; i >= 0; i--) { int temp = (str[i] - '0') * 2 + carry; carry = temp / 10; char tempChar = (temp % 10 + '0') ; result = tempChar + result; } if (carry != 0) result = "1" + result; return result; } string add(string str, int x) { string result; int carry = x; for (int i = str.size() - 1; i >= 0; i--) { int temp = str[i] - '0' + carry; carry = temp / 10; char tempChar = (temp % 10 + '0'); result = tempChar + result; } if (carry != 0) result = "1" + result; return result; } int main() { string a; while (cin >> a ) { // 注意 while 处理多个 case vector<int> binary; while (a.size() > 0) { binary.push_back((a[a.size() - 1] - '0') % 2); a = divide(a); } string b = "0"; for (int i = 0; i < binary.size(); i++) { b = multiple(b); b = add(b, binary[i]); } cout << b << endl; } } // 64 位输出请用 printf("%lld")