Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
思路:模仿整数加法。
AC代码:
class Solution {
public:
string addBinary(string a,string b)
{
reverse(a.begin(), a.end());
reverse(b.begin(), b.end());
int f = 0;//进位标志位
if(a.length()>b.length()) swap(a,b);
string res(b);
for(int i=0;i<a.length();i++)
{
res[i] += ((a[i]-'0') + f);
if(res[i]>'1')
{
res[i] -= 2;
f = 1;
}
else f = 0;
}
for(int i=a.length();i<b.length();i++)
{
res[i] += f;
if(res[i]>'1')
{
res[i] -= 2;
f = 1;
}
else f = 0;
}
if(f==1)
res+="1";
reverse(res.begin(), res.end());
return res;
}
};
结束语:其他进制的计算类似,只需要把2改成相应进制即可。