Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题目并不复杂,以下是我的程序,后面是别人的程序,瞬间low了好大一截!
冗长!!!!!!!
class Solution {
public:
string addBinary(string a, string b) {
string result;
bool more=false;
int i,j;
for(i=a.size()-1,j=b.size()-1;i>=0 && j>=0;i--,j--)
{
if(!more)
{
if(a[i]=='0' && b[j]=='0')
{
result.push_back('0');
}
else if((a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0'))
{
result.push_back('1');
}
else
{
result.push_back('0');
more=true;
}
}
else
{
if(a[i]=='0' && b[j]=='0')
{
result.push_back('1');
more=false;
}
else if((a[i]=='0' && b[j]=='1') || (a[i]=='1' && b[j]=='0'))
{
result.push_back('0');
more=true;
}
else
{
result.push_back('1');
more=true;
}
}
}
string c=(i>=0?a:b);
int k=(i>=0?i:j);
for(;k>=0;k--)
{
if(!more)
{
result.push_back(c[k]);
}
else
{
if(c[k]=='0')
{
result.push_back('1');
more=false;
}
else
{
result.push_back('0');
more=true;
}
}
}
if(more)
result.push_back('1');
reverse(result.begin(),result.end());
return result;
}
};
大神的
循环判断自增一体,简洁有力!!!!!差距啊
struct Solution {
string addBinary(string a, string b) {
if (a.size() < b.size())
swap(a, b);//直接保存在a中,不用辅助空间
int i = a.size(), j = b.size();
while (i--) {
if (j) a[i] += b[--j] & 1;//‘0’& 1为0 ,‘1’& 1为1
if (a[i] > '1') {//如果需要进位
a[i] -= 2;//进位后的字符
if (i)
a[i-1]++; //进位
else
a = '1' + a;//增加一位
}
}
return a;
}
};