题解 | #10进制 VS 2进制#

10进制 VS 2进制

https://www.nowcoder.com/practice/fd972d5d5cf04dd4bb4e5f027d4fc11e

难点在于字符串实现加法和乘除

#include <iostream>
#include <vector>
using namespace std;
string divide(string str) {
    int remain = 0;
    string result;
    for (int i = 0; i < str.size(); i++) {
        int temp = remain * 10 + str[i] - '0';
        remain = temp % 2;
        char tempChar = (temp / 2 + '0');
        result += tempChar;
    }
    if (result == "0") return "";
    else {
        int pos = 0;
        while (result[pos] == '0') pos++;
        return result.substr(pos);
    }
}
string multiple(string str) {
    string result;
    int carry = 0;
    for (int i = str.size() - 1; i >= 0; i--) {
        int temp = (str[i] - '0') * 2 + carry;
        carry = temp / 10;
        char tempChar = (temp % 10 + '0') ;
        result = tempChar + result;
    }
    if (carry != 0) result = "1" + result;
    return result;
}
string add(string str, int x) {
    string result;
    int carry = x;
    for (int i = str.size() - 1; i >= 0; i--) {
        int temp = str[i] - '0' + carry;
        carry = temp / 10;
        char tempChar = (temp % 10 + '0');
        result = tempChar + result;
    }
    if (carry != 0) result = "1" + result;
    return result;
}
int main() {
    string a;
    while (cin >> a ) { // 注意 while 处理多个 case
        vector<int> binary;
        while (a.size() > 0) {
            binary.push_back((a[a.size() - 1] - '0') % 2);
            a = divide(a);
        }
        string b = "0";
        for (int i = 0; i < binary.size(); i++) {
            b = multiple(b);
            b = add(b, binary[i]);
        }
        cout << b << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务