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) {
int c = 0, quo = 0, i, j;
string ans;
for(i = a.length() - 1, j = b.length() - 1; i >= 0 || j >= 0; --i, --j){
if(i >= 0 && j >= 0){
quo = (a[i] - '0' + b[j] - '0' + c) % 2;
c = (a[i] - '0' + b[j] - '0' + c) / 2;
} else if(i >= 0){
quo = (a[i] - '0' + c) % 2;
c = (a[i] - '0' + c) / 2;
} else if(j >= 0){
quo = (b[j] - '0' + c) % 2;
c = (b[j] - '0' + c) / 2;
}
ans.insert(ans.begin(), (quo + '0'));
}

if(c != 0)
ans.insert(ans.begin(), (c + '0'));
return ans;
}
};

class Solution {
public:
string addBinary(string a, string b) {
string res;
int i, j, carry = 0;
for(i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; --i, --j){
res.push_back((a[i] - '0' + b[j] - '0' + carry) % 2 + '0');
carry = (a[i] - '0' + b[j] - '0' + carry) / 2;
}
while(i >= 0){
res.push_back((a[i] - '0' + carry) % 2 + '0');
carry = (a[i] - '0' + carry) / 2;
--i;
}
while(j >= 0){
res.push_back((b[j] - '0' + carry) % 2 + '0');
carry = (b[j] - '0' + carry) /  2;
--j;
}
if(carry) res.push_back('1');

string rev;
int len = res.length();
for(i = len - 1; i >= 0; --i){
rev.push_back(res[i]);
}
return rev;
}
};
• 本文已收录于以下专栏：

举报原因： 您举报文章：67. Add Binary 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)