题解 | #10进制 VS 2进制#
10进制 VS 2进制
https://www.nowcoder.com/practice/fd972d5d5cf04dd4bb4e5f027d4fc11e
本题相较于KY30 进制转换,多了一个字符串二进制转十进制的操作。对于转换公式:
我们观察该公式,我们可以设计出如下两个函数,一个负责乘,一个负责加:
这里的乘,具体来说就是求一个字符串乘2的结果。而加,就是求字符串加上一个数字的结果
我们可以从得到的二进制的最高位开始,让它做乘,就得到bn x 2,再加上bn-1,得到bn x 2 + bn-1,再乘2,得到(bn x 2 + bn-1) x 2 = bn x 2^2 + bn-1 x 2,就这样不断进行下去,就能够得到x。
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
void divide(string& num){
int remainder = 0;
for(int i = 0; i < num.size(); i++){
int current = remainder * 10 + num[i] - '0';
num[i] = current / 2 + '0';
remainder = current % 2;
}
int pos = 0;
while(num[pos] == '0'){
pos++;
}
num = num.substr(pos);
}
string multiply(string reverse){
int plus = 0;
for(int i = reverse.size() - 1; i >= 0; i--){
int current = (reverse[i] - '0') * 2 + plus;
plus = current / 10;
reverse[i] = current % 10 + '0';
}
if(plus != 0) reverse = "1" + reverse;
return reverse;
}
string add(string reverse, int n){
int plus = n;
for(int i = reverse.size() - 1; i >= 0; i--){
int current = reverse[i] - '0' + plus;
plus = current / 10;
reverse[i] = current % 10 + '0';
}
if(plus != 0) reverse = "1" + reverse;
return reverse;
}
int main() {
string num;
cin >> num;
vector<int> binary;
while(!num.empty()){
binary.push_back(num[num.size() - 1] % 2);
divide(num);
}
string reverse = "0";
for(int i = 0; i < binary.size(); i++){
reverse = multiply(reverse);
reverse = add(reverse, binary[i]);
}
cout << reverse;
}
// 64 位输出请用 printf("%lld")


vivo公司福利 364人发布