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

}

全部评论

相关推荐

我见java多妩媚:大外包
点赞 评论 收藏
分享
11-09 01:22
已编辑
东南大学 Java
高级特工穿山甲:羡慕,我秋招有家企业在茶馆组织线下面试,约我过去“喝茶详谈”😢结果我去了发现原来是人家喝茶我看着
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务