67.AddBinary
跟66.Plus One 差不多,我还是先把他翻转过来。
因为有可能两个字符串长度不一样。短的字符串如果超出长度,循环时一直加0就好了。
class AddBinary {
public:
string addBinary(string a, string b) {
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
string str;
int nSize = a.size() > b.size() ? a.size() : b.size();
int jinwei = 0;
for (int i = 0; i < nSize; i++)
{
int aVal = 0;
int bVal = 0;
if (i >= a.size())
{
aVal = 0;
}
else
{
aVal = a[i] - '0';
}
if (i >= b.size())
{
bVal = 0;
}
else
{
bVal = b[i] - '0';
}
int nSum = aVal ^ bVal ^ jinwei;
str += '0' + nSum;
if ((aVal & bVal == 1) || (aVal & jinwei == 1) || (bVal & jinwei) == 1)
{
jinwei = 1;
}
else
{
jinwei = 0;
}
}
if (jinwei == 1)
{
str.push_back('1');
}
reverse(str.begin(), str.end());
return str;
}
};