【牛客网】KY26 10进制 VS 2进制

在这里插入图片描述
题目要求已经很明确地说了解题步骤,所以只需要按照步骤来即可,难点就在于字符串的乘除,对于这个,我们可以借助STL的vector来解决,首先十进制转换为二进制的过程中,用个位上的数对2取余存入到vector中,由于模2取余的结果是从后往前的,那么从前往后就是逆序,因此vector中存放的就是逆序,之后再根据vector的值依次乘以2即可得到最终的结果:

#include<iostream>
#include<string>
#include<vector>

using namespace std;

string Divide(string str, int x){
    int remainder = 0;
    int n = str.size();
    for(int i = 0;i < n;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 Multiply(string str, int x){
    int c = 0;  //进位
    int n = str.size();
    for(int i = n - 1;i >= 0;i--){
        int current = (str[i] - '0') * x + c;
        str[i] = current % 10 + '0';
        c = current / 10;
    }
    if(c > 0) str = "1" + str;  //两个个位数相加最多进位1
    return str;
}

string Add(string str, int x){
    int c = x;
    int n = str.size();
    for(int i = n - 1;i >= 0;i--){
        int current = str[i] - '0' + c;
        str[i] = current % 10 + '0';
        c = current / 10;
        if(c == 0) break;
    }
    return str;
}

int main(){
    string s;
    while(cin>>s){
        vector<int> v;
        while(s.size() != 0){  //先将十进制转换为二进制,将余数依次存入v中即实现了逆序
            int last = s[s.size() - 1] - '0';
            v.push_back(last % 2);
            s = Divide(s, 2);
        }
        string total = "0";
        int n = v.size();
        for(int i = 0;i < n;i++){
            total = Multiply(total, 2);
            total = Add(total, v[i]);
        }
        cout<<total<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

花无凋零之时

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值