题解 | #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");
    }

}

全部评论

相关推荐

11-08 13:58
门头沟学院 Java
程序员小白条:竟然是蓝桥杯人才doge,还要花钱申领的offer,这么好的公司哪里去找
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务