难点在于实现模拟人手动计算加法和乘法的过程 #include<vector> #include<string> #include<iostream> #include<cstdio> #include<cmath> using namespace std; string Divde(string str, int x) { int remainder = 0; for (int i = 0; i < str.size(); i++) { int temp = remainder * 10 + str[i] - '0'; str[i] = temp / x +'0'; remainder = temp % 2; } int pos = 0; while (str[pos++] == '0'); pos--; str = str.substr(pos); return str; } string Multiple(string str,int x) { //实现字符串的乘法 int carry = 0; // 保存进位 for (int i = str.size() - 1; i >= 0; i--) { int current = x * (str[i] - '0') + carry; str[i] = current % 10 + '0'; carry = current / 10; } if (carry != 0) str = "1" + str; return str; } string Add(string str, int x) { //实现字符串的加法 int carry = x;//记录进位 for (int i = str.size() - 1; i >= 0; i--) { int temp = (str[i]-'0') + carry; str[i] = temp % 10+'0'; carry = temp / 10; } if (carry != 0) str = "1" + str; return str; } int main() { string str; while (cin >> str) { vector<int> vec; while (str != "") { vec.push_back((str[str.size()-1 ]-'0') % 2); str = Divde(str, 2); } //此时得到便为二进制的逆序 string answer = "0"; for (int i =0; i < vec.size(); i++) { answer = Multiple(answer, 2); answer = Add(answer, vec[i]); } cout << answer << endl; } }