Description
Submission
class Solution {
public:
string addBinary(string a, string b) {
if(a.size() < b.size()) swap(a, b);
if(b == "0") return a;
if(a == "0") return b;
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string res;
int carry = 0;
for(int i = 0; i < b.size(); ++i) {
int sum = a[i] - '0' + b[i] - '0' + carry;
carry = 0;
if(sum < 2) res.push_back('0' + sum);
else {
carry = 1;
res.push_back('0' + sum - 2);
}
}
if(a.size() == b.size()) res.push_back(carry + '0');
else {
for(int i = b.size(); i < a.size(); ++i) {
char sum = a[i] + carry;
carry = 0;
if(sum < '2') {
res.push_back(sum);
} else {
carry = 1;
res.push_back(sum - 2);
}
}
if(carry == 1) res.push_back('1');
}
reverse(res.begin(), res.end());
return res;
}
};