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) {
swap( a, b);
int lenA = a.length();
int lenB = b.length();
int j = lenB-1;
int he, jingwei;
jingwei = 0;
string ans = "";
for (int i = lenA - 1; i >= 0; i--)
{
if (j >= 0){
he = (a[i] - '0') + (b[j] - '0') + jingwei;
}
else he = (a[i] - '0') + jingwei ;
jingwei= he / 2;
he = he % 2;
ans += to_string(he);
j--;
}
if (jingwei) ans += '1';
reverse(ans.begin(), ans.end());
return ans;
}
void swap(string & a, string & b)
{
string temp;
if (b.length() > a.length())
{
temp = a;
a = b;
b = temp;
}
}
};