Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Seen this question in a real interview before?
Yes
分析:二进制下的字符串的加法
class Solution {
public:
string addBinary(string a, string b) {
string result = "";
int c=0;
int i = a.size()-1;
int j = b.size()-1;
while(i>=0||j>=0||c==1)
{
if(i>=0)
c+=a[i--]-'0';
if(j>=0)
c+=b[j--]-'0';
result = char(c%2+'0')+result;
c=c/2;
}
return result;
}
};