[67] leetcode binary sum (array)

Topic links: https://leetcode-cn.com/problems/add-binary/submissions/

Title Description

Given two binary string, and return to their (expressed in binary).

And a non-empty input string contains only numbers 0 and 1.

Example 1:

输入: a = "11", b = "1"
输出: "100"

Example 2:

输入: a = "1010", b = "1011"
输出: "10101"

Code

class Solution {
public:
    string addBinary(string a, string b) {
        int i = a.size()-1;
        int j = b.size()-1;
        bool carry = false;
        string ret;
        while (i>=0 && j>=0){
            bool m = (a[i] == '1');
            bool n = (b[j] == '1');
            a[i] = m^n^carry + '0';
            carry = int(m + n + carry) > 1;
            --i,--j;
        }
        while (i>=0){
            bool m = (a[i] == '1');
            a[i] = m^carry + '0';
            carry = m && carry;
            --i;
        }
        while (j>=0){
            bool n = (b[j] == '1');
            if(n^carry)
                a.insert(a.begin(),'1');
            else
                a.insert(a.begin(),'0');
            carry = n && carry;
            --j;
        }
        if(carry)
            a.insert(a.begin(),'1');
        return a;
    }
};

Here Insert Picture Description

Simplify the code

class Solution {
public:
    string addBinary(string a, string b) {
        int i = a.size()-1;
        int j = b.size()-1;
        int carry = 0;
        string ret;
        while (i>=0 || j>=0 || carry!=0){
            int digitA = i >= 0? a[i--] - '0' :0;
            int digitB = j >= 0? b[j--] - '0' :0;
            ret.push_back((digitA + digitB + carry) %2 +'0');
            carry = (digitA + digitB + carry) /2; 
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }
};

Here Insert Picture Description

Guess you like

Origin blog.csdn.net/zjwreal/article/details/94606417