Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
class Solution {
public:
string addBinary(string a, string b) {
if(a.size() < b.size()) return addBinary(b, a);
if(b.size() <= 0) return a;
vector<char> v = vector<char>();
int carry = 0;
for(int i=a.size()-1, j = b.size()-1;j>=0;i--,j--){
int t = a[i] + b[j] - '0' - '0' + carry;
v.push_back(t % 2 + '0');
carry = t / 2;
}
for(int i=a.size() - b.size() - 1;i>=0;i--){
int t = a[i] - '0' + carry;
v.push_back(t % 2 + '0');
carry = t / 2;
}
if(carry == 1) v.push_back(1 + '0');
reverse(v.begin(), v.end());
string r = string(v.begin(), v.end());
return r;
}
};