模拟手工除法的过程 #include<vector> #include<string> #include<iostream> #include<cstdio> using namespace std; string Divide(string str, int x) { // 模拟手工计算除以2的过程 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 % x; } int pos = 0; while (str[pos] == '0') { pos++; } str = str.substr(pos); return str; } int main() { string str; vector<int> vec; while (cin >> str) { if (str == "0") { cout << "0"<<endl; continue; } vec.clear(); while (str != "") { //str不等于空串的时候 vec.push_back((str[str.size() - 1] - '0') % 2); str = Divide(str, 2); } for (int i = vec.size() - 1; i >= 0; i--) { cout << vec[i]; } cout << endl; } }