总是犯无脑的错误,没返回结果,字符串转数字没减‘0’,进位的关系没搞清楚,提交了无数次才通过
class Solution {
public:
string addBinary(string a, string b) {
string res;
int lena=a.size()-1;
int lenb=b.size()-1;
int carry=0;
int sum=0;
while(lena!=-1&&lenb!=-1)
{
sum=carry+a[lena]+b[lenb]-'0'*2;
carry=(sum-2)>=0?1:0;
sum=(carry>0)?(sum-2):sum;
res.insert(res.begin(),sum+'0');
lena--;
lenb--;
}
while(lena!=-1)
{
sum=carry+a[lena]-'0';
carry=(sum-2)>=0?1:0;
sum=(carry>0)?(sum-2):sum;
res.insert(res.begin(),sum+'0');
lena--;
}
while(lenb!=-1)
{
sum=carry+b[lenb]-'0';
carry=(sum-2)>=0?1:0;
sum=(carry>0)?(sum-2):sum;
res.insert(res.begin(),sum+'0');
lenb--;
}
if(carry>0)
res.insert(res.begin(),carry+'0');
return res;
}
};