题解 | #10进制 VS 2进制#
10进制 VS 2进制
https://www.nowcoder.com/practice/fd972d5d5cf04dd4bb4e5f027d4fc11e
//
// Created by Virtus on 2024/2/22.
//
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 字符串除法
string stringDivide(string str, int x) {
int remainder = 0;
for (char & i : str) {
int current = remainder * 10 + i - '0';
i = current / x + '0';
remainder = current % x;
}
int pos = 0;
while (str[pos] == '0') {
pos++;
}
return str.substr(pos);
}
// 字符串乘法
string stringMultiple(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 stringAdd(string str, int x) {
int carry = x;
for (int i = str.size() - 1; i >= 0; --i) {
int current = (str[i] - '0') + carry;
str[i] = current % 10 + '0';
carry = current / 10;
}
if (carry != 0) {
str = "1" + str;
}
return str;
}
int main() {
string str;
while (cin >> str) {
vector<int> binary;
while(!str.empty()) {
int last = str[str.size() - 1] - '0';
binary.push_back(last % 2);
str = stringDivide(str, 2);
}
string answer = "0";
for (int i : binary) {
answer = stringMultiple(answer, 2);
answer = stringAdd(answer, i);
}
cout << answer << endl;
}
return 0;
}
查看14道真题和解析
网易游戏公司福利 592人发布