Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Code:
<span style="font-size:14px;">class Solution {
public:
string addBinary(string a, string b) {
int lengthA = a.size(), lengthB = b.size();
if (lengthA == 0) return b;
if (lengthB == 0) return a;
if (lengthA < lengthB)
a = string(lengthB-lengthA, '0')+a;
else if (lengthA > lengthB)
b = string(lengthA-lengthB, '0')+b;
int carry = 0, sum;
lengthA = max(lengthA, lengthB);
for (int i = lengthA-1; i >= 0; --i) {
sum = carry+a[i]-'0'+b[i]-'0';
carry = sum/2;
a[i] = sum%2+'0';
}
if (carry) a = "1"+a;
return a;
}
};</span>