题解 | #10进制 VS 2进制#
10进制 VS 2进制
https://www.nowcoder.com/practice/fd972d5d5cf04dd4bb4e5f027d4fc11e
#include <iostream> #include <vector> using namespace std; string Divide(string str, int x) { //x进制 int remainder = 0; for (int i = 0; i < str.size(); i++) { int current = remainder * 10 + str[i] - '0'; remainder = (current) % x; str[i] = current / x + '0'; // printf("str[%d]=%c",i,str[i]); } 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 = (str[i] - '0') * x + carry; carry = current / 10; str[i] = current % 10 + '0'; } 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; carry = current / 10; str[i] = current % 10 + '0'; } if (carry != 0) { str = "1" + str; } return str; } int main() { string str; while (getline(cin, str)) { //173 vector<int> binary; while (str.size() != 0) { int last = str[str.size() - 1] - '0'; binary.push_back(last % 2); // printf("接下来要除的是:"); str = Divide(str, 2); // cout<<str<<endl; // printf("\n"); } // cout<<str<<endl; //二进制数转成十进制数: string answer = "0"; for (int i = 0; i < binary.size(); i++) { answer = multiple(answer, 2); answer = ADD(answer, binary[i]); } cout << answer << endl; // printf("\n"); } }