题解 | #进制转换#
进制转换
https://www.nowcoder.com/practice/0337e32b1e5543a19fa380e36d9343d7
#include <bits/stdc++.h>
using namespace std;
//这是答案的除法
string Divide(string str,int x) { //字符串除法int remainder = 0; //保存余数
int remainder = 0;
for (int i = 0; i < str.size(); ++i) {
int current = remainder * 10 + str[i] - '0';
str[i] = current / x + '0';
remainder = current % x;
}
int pos = 0;
while (str[pos] == '0') {
pos++; //寻找首个非0 下标
}
return str.substr(pos); //删除前置多余的0}
}
// 这是我调试了很久的除法 呜呜呜!!!
string divide(string str) {
if (str.size() == 1) {
string res = "";
res += (str[0] - '0') / 2 + '0';
return res;
}
string res = "";
int yushu = 0;
for (int i = 0; i < str.size(); i++) { //从数的高位到低位遍历
int num = str[i] - '0' + yushu * 10; //先将每一位的字符转换为整数
if (num % 2 == 0) { //如果能整除 则该位为除法之后的数
res += '0' + num / 2; //添加进res中
yushu = 0; //此时余数为0
}
else { //若不能被整除
yushu = 1;
int temp = num / 2; //获得该位的值
if(i != 0 || temp != 0){ //如果第一位高位为0 不需要添加 其他情况都要添加字符
res += temp + '0';
}
}
}
return res;
}
int main() {
string num;
while (cin >> num) { // 注意 while 处理多个 case
if (num == "0") {
cout << 0 << endl;
continue;
}
stack<int> s;
while ( num != "" && num != "0") {
int t = (num[num.size() - 1] - '0') % 2; //对低位求余
s.push(t); //压入栈中
num = divide(num); //num 除以 2
}
while (!s.empty()) {
cout << s.top();
s.pop();
}
cout << endl;
}
}
// 64 位输出请用 printf("%lld")
#考研复试#
查看14道真题和解析
