Eay to understand C++


#1

string Solution::addBinary(string A, string B) {
reverse(A.begin(),A.end());
reverse(B.begin(),B.end());
int carry=0;
int n=A.length();
int m=B.length();
int k=min(n,m);
string ans;
for(int i=0;i<k;i++)
{
if(carry+A[i]-‘0’+B[i]-‘0’==2)
{
ans+=“0”;
carry=1;
}
else if(carry+B[i]-‘0’+A[i]-‘0’>2)
{
ans+=“1”;
carry=1;
}
else
{
ans+=to_string(carry+A[i]-‘0’+B[i]-‘0’);
carry=0;
}
}
// cout<<ans<<endl;
if(k==n)
{
for(int i=n;i<m;i++){
if(carry+B[i]-‘0’==2)
{
ans+=“0”;
carry=1;
}
else if(carry+B[i]-‘0’>2)
{
ans+=“1”;
carry=1;
}
else
{
ans+=to_string(carry+B[i]-‘0’);
carry=0;
}
}
if(carry==1)ans+=‘1’;
}
else
{

    for(int i=m;i<n;i++){
        if(carry+A[i]-'0'>1)
        {
            ans+="0";
            carry=1;
        }
        else if(carry+A[i]-'0'>2)
        {
            ans+="1";
            carry=1;
        }
        else
        {
            ans+=to_string(carry+A[i]-'0');
            carry=0;
        }
    }
    if(carry==1)ans+='1';
}
reverse(ans.begin(),ans.end());
return ans;

}