# C++ Solution 4ms with comments

• ``````class Solution {
public:
string addBinary(string a, string b) {
//Always have it so that string a is the longer string
if(b.size() > a.size()) return addBinary(b, a);

string res;
bool carry = false;
int aIndex = a.size() - 1;

//Iterate from the end of the shorter string, b, and add digits
//one by one.
for(int i = b.size() - 1; i >= 0; i--) {
char summed = addDigits(b[i], a[aIndex], carry);
res.push_back(summed);
aIndex--;
}

//If there are any characters left in the longer string,
//we need to add each of them as well.
for(int i = aIndex; i >= 0; i--) {
char summed = addDigits(a[i], '0', carry);
res.push_back(summed);
}

//If there is a carry at the end of all adding, we push
//an additional one into the string.
if(carry) res.push_back('1');

//Reverse the string and return the result
reverse(res.begin(), res.end());
return res;
}

char addDigits(char d1, char d2, bool &carry) {
if(carry) {
if(d1 == '0' && d2 == '0') carry = false;

if(d1 == d2) return '1';
else return '0';
} else {
if(d1 == '1' && d2 == '1') carry = true;

if (d1 == d2) return '0';
else return '1';
}
}
};
``````

Pretty straight forward solution. Modularized into an addDigits function to reduce code duplication.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.