<p>Given two binary strings <code>a</code> and <code>b</code>, return <em>their sum as a binary string</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> a = "11", b = "1"
<strong>Output:</strong> "100"
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> a = "1010", b = "1011"
<strong>Output:</strong> "10101"
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= a.length, b.length &lt;= 10<sup>4</sup></code></li>
	<li><code>a</code> and <code>b</code> consist&nbsp;only of <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code> characters.</li>
	<li>Each string does not contain leading zeros except for the zero itself.</li>
</ul>

class Solution {
public:
    string addBinary(string a, string b) {
        int A = a.length();
        int B = b.length();
        string ans;
        int carry = 0;
        
        // Make both strings of equal length by padding with '0's on the left
        if (A < B) {
            a = string(B - A, '0') + a;  // pad with zeros
        } else {
            b = string(A - B, '0') + b;
        }
        
        // Traverse from the last character to the first
        for (int i = a.length() - 1; i >= 0; i--) {
            int sum = (a[i] - '0') + (b[i] - '0') + carry; // Convert char to int and add carry
            if (sum == 2) {
                ans += '0';  // 1 + 1 gives 0 with a carry
                carry = 1;
            } else if (sum == 3) {
                ans += '1';  // 1 + 1 + 1 gives 1 with a carry
                carry = 1;
            } else {
                ans += (sum + '0'); // If sum is 0 or 1, directly add to result
                carry = 0;
            }
        }
        
        // If there's still a carry left, add it to the result
        if (carry) {
            ans += '1';
        }
        
        // The result is built in reverse, so reverse it before returning
        reverse(ans.begin(), ans.end());
        return ans;
    }
};

8500