题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/0337e32b1e5543a19fa380e36d9343d7
//十进制转二进制,采用除留余数法。因30位十进制数太大,采用字符串存储。
#include <cstddef>
#include <iostream>
#include <string>
using namespace std;
int main() {
string n;
while (cin >> n) {
string str = "";
if (n == "0") str = "0";
n.insert(0, "z");//作为开头字符
while (n != "z0") {
int a;
if ((n[n.size() - 1] - 48) % 2 == 0) {//最后一个数字是否是偶数
str.insert(0, "0");
}
else {
str.insert(0, "1");
n[n.size() - 1] = n[n.size() - 1] - 1;//减去余数
}
if (n != "z0") {
int yushu = 0, next;//进行字符串除2
for (int i = 1; i < n.size(); i++) {
next = (yushu * 10 + n[i] - 48) % 2;
a = (yushu * 10 + n[i] - 48 - next) / 2;
string c = to_string(a);
if (n[i - 1] == 'z' && n[i + 1] != '\0' && c == "0") {//将无效的0去除
n.erase(i, 1);
i--;
}
else {
n.erase(i, 1);
n.insert(i, c);
}
yushu = next;
}
}
}
cout << str << endl;
}
return 0;
}