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 sa = a.size();
int sb = b.size();
int flag = 0,da = 0;
string res;
for (sa,sb;sa>0 && sb > 0;sa--,sb--)
{
int temp = (int)(a[sa-1]-'0') + (b[sb-1]-'0')+flag;
flag = temp / 2;
da = temp % 2;
res.push_back(da+'0');
}
while (sa)
{
int temp = (int)(a[sa-1]-'0')+flag;
flag = temp / 2;
da = temp % 2;
res.push_back(da+'0');
sa--;
}
while (sb)
{
int temp = (int)(b[sb-1]-'0')+flag;
flag = temp / 2;
da = temp % 2;
res.push_back(da+'0');
sb--;
}
if (flag == 1)
res.push_back(flag+'0');
reverse(res.begin(),res.end());
return res;
}
};