c_cpp 添加两个binarys,返回二进制文件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 添加两个binarys,返回二进制文件相关的知识,希望对你有一定的参考价值。

// version 1, use string "reverse", from left to right
string add_binary(string& b1, string& b2) { // cannot use const because of "reverse" method
    if(b1.empty()) return b2;
    if(b2.empty()) return b1;
    reverse(b1.begin(), b1.end());
    reverse(b2.begin(), b2.end());
    string res;
    int i = 0, j = 0, carry = 0;
    while(i < b1.size() || j < b2.size()) {
        int d1 = i < b1.size() ? b1[i] - '0' : 0;
        int d2 = j < b2.size() ? b2[j] - '0' : 0;
        int d = d1 + d2 + carry;
        if(d >= 2) carry = 1;
        else carry = 0;
        res += d%2 + '0';
        i++;
        j++;
    }
    if(carry == 1) res += '1';
    reverse(res.begin(), res.end());
    return res;
}

// better version, without string reversion. from right to left
string add_binary(const string& b1, const string& b2) {
    if(b1.empty()) return b2;
    if(b2.empty()) return b1;
    string res = "";
    int i = b1.size()-1, j = b2.size()-1, carry = 0;
    while(i >= 0 || j >= 0) {
        int d1 = i >= 0 ? b1[i] - '0' : 0;
        int d2 = j >= 0 ? b2[j] - '0' : 0;
        int d = d1 + d2 + carry;
        if(d >= 2) carry = 1;
        else carry = 0;
        if(d%2 == 0)
            res = "0" + res;
        else if(d%2 == 1)
            res = "1" + res;
        //res = d%2 + '0' + res;        // gist, char cannot "left add" a string. Should use "0" not '0'
        i--;
        j--;
    }
    if(carry == 1) res = "1" + res;
    return res;
}

int main()
{
    string s1 = "100", s2 = "100";
    cout << add_binary(s1, s2);
}

以上是关于c_cpp 添加两个binarys,返回二进制文件的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 67.添加Binary-DifficultyEasy - 2018.8.23

c_cpp 添加Binaryhttp://oj.leetcode.com/problems/add-binary/

LeetCode.868-二进制距离(Binary Gap)

LeetCode 67 Add Binary(二进制相加)(*)

67. Add Binary [easy] (Python)

LeetCode 67 Add Binary(二进制相加)(*)