1 minute read

<-E 67> Add Binary

class Solution {
public:
    string addBinary(string a, string b) {
        
        const int aLength = a.length();
        const int bLength = b.length();
        const int resultLength = max(aLength, bLength) + 1;

        char temp[resultLength + 1];
        temp[resultLength] = '\0';

        int resultIndex = resultLength - 1;
        int carry = 0;

        for(int i = aLength-1, j = bLength-1; i>=0 || j >=0; i--, j--, resultIndex--) {
            const int aVal = (i >= 0 ? a[i] : '0') - '0';
            const int bVal = (j >= 0 ? b[j] : '0') - '0';
            const int sum = aVal + bVal + carry;
            temp[resultIndex] = (sum % 2) + '0';
            carry = sum / 2;
        }

        char* result = &temp[resultIndex];
        
        if (carry > 0)
            result[resultIndex] = carry + '0';
        else
            result++;

        return result;
    }
};



class Solution {
public:
    string addBinary(string& a, string& b) {
        int n = max(a.size(), b.size());
        string s;
        s.reserve(n + 1);
        
        int carry = 0;
        int i = a.size();
        int j = b.size();
        while (i || j || carry) {
            int current_pos_sum = carry;
            if (i) current_pos_sum += (a[--i] == '1' ? 1 : 0);
            if (j) current_pos_sum += (b[--j] == '1' ? 1 : 0);
            
            s.push_back((current_pos_sum % 2 == 1) ? '1' : '0');
            carry = current_pos_sum / 2;
        }
        reverse(s.begin(), s.end());
        return s;
    }
};