Implementation like Carry Look Ahead Adder in Digital circuits

programming
Tags: #<Tag:0x00007f18264ef7b0>

#1

string Solution::addBinary(string A, string B) {
string c;
if(B.length()>A.length())
swap(A,B);
for(int i=0;i<A.length()-B.length();i++)
{
c+=“0”;
}
c+=B;
B=c;
int n=A.length();
char carry=‘0’;
string sum;
for(int i=n-1;i>=0;i–)
{
int a,b,c;
a=(A[i]==‘1’)?1:0;
b=(B[i]==‘1’)?1:0;
c=(carry==‘1’)?1:0;
int add=a^b^c;
int ca=(a&b)|(b&c)|(c&a);
if(ca==0)
carry=‘0’;
else
carry=‘1’;
if(add==0)
sum+=‘0’;
else
sum+=‘1’;
}
if(carry==‘1’)
sum+=carry;
reverse(sum.begin(),sum.end());
return sum;
}