C++ 这题简单
#include<string>
#include<algorithm>
using namespace std;
//对s除以2
string div2(string s) {
//cout << "div2输入:s=" << s << endl;
while (s[0] == '0') {//去掉左侧的零
s.erase(0, 1);
}
if (s == "")return "0";
//一般情况
int carry = 0;
for (int i = 0; i < s.size(); i++) {
if ((s[i] +carry - '0') % 2 == 1) {
s[i] = (s[i] + carry - '0') / 2 + '0';
carry = 10;
}
else {
s[i] = (s[i] + carry - '0') / 2 + '0';
carry = 0;
}
}
while (s[0] == '0') {//去掉左侧的零
s.erase(0, 1);
}
//cout << "div2结果:s=" << s << endl;
return s;
}
//将s转成二进制数,采用除2取余法
string f(string s) {
if (s == "" || s == "0")return "0";
string res = "";
while (s != "") {
res += (s[s.size() - 1] - '0') % 2 + '0';
s = div2(s);
}
reverse(res.begin(), res.end());
return res;
}
int main() {
string s;
while (cin >> s) {
cout << f(s) << endl;
}
return 0;
}