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;
}
};