题解 | 10进制 VS 2进制

#include<iostream>
#include<cmath>

using namespace std;

string chu(string n) { //实现n/2
    int y, z, c = 0;
    for (int i = 0; i < n.size(); i++) { //实现n/2
        y = n[i] - '0' + c * 10;
        z = y % 2;
        y = y / 2;
        if (z != 0) {
            c = 1;
        } else c = 0;
        n[i] = y + '0';
    }
    if (n[0] == '0')n.erase(0, 1);
    return n;
}
string cheng(string n, int x) { //实现乘法
    int y, z, c = 0;
    for (int i = n.size() - 1; i >= 0; i--) {
        y = x * (n[i] - '0') + c;
        z = y % 10;
        c = y / 10;
        n[i] = z + '0';
    }
    if (c != 0)n.insert(0, "1");
    return n;
}
string add(string n, int x) {
    int y, z, c = x;
    for (int i = n.size() - 1; i >= 0; i--) {
        y = n[i] - '0' + c;
        z = y % 10;
        c = y / 10;
        n[i] = z + '0';
    }
    if (c != 0)n.insert(0, "1");
    return n;
}
int main() {
    string n, t;
    cin >> n;
    while (!n.empty()) { //变为逆序
        int x = n[n.size() - 1] - '0';
        if (x % 2 == 0) t += "0";
        else t += "1";
        n = chu(n);
    }
    string ans;
    for (int i = 0; i < t.size(); i++) { //二进制数转为十进制
        ans = cheng(ans, 2);
        int temp = t[i] - '0';
        ans = add(ans, temp);
    }
    cout << ans << endl;
}

全部评论

相关推荐

想做乐观锁:都不用AI,咱们都古法编程吧,让节奏慢一点
点赞 评论 收藏
分享
小牛炒肉:好大的官威居然不是什么官
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务