举个例子说明代码:原数为8,8的二进制序列为1000,题目经过除法后binary里序列为0001,即为逆序后的二进制序列,只需对其还原为十进制,此处用的方法是
结果 = (2^3 x 0 + 2^2 x 0+ 2^1 x 0 + 2^0 x 1)
加上binary的位是将为1的位加入结果的计算中,因为后续每一次multiple都会对其构成部分乘2,最终达到其所在位置上的权值
#include <iostream>
#include <vector>
using namespace std;
string divide(string str, int x) { //字符串除法
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++;
}
return str.substr(pos);
}
string multiple(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 add(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.size() != 0) {
int last = str[str.size() - 1] - '0';
binary.push_back(last % 2);
str = divide(str, 2);
}
string answer = "0";
for (int i = 0; i < binary.size(); ++i) {
answer = multiple(answer, 2);
answer = add(answer, binary[i]);
}
cout << answer << endl;
}
}