//xor can perfectly simulate the addition operation
void add(int a, int b)
{
int result=0;
int c=0;
for(int i=0;i<32;i++)
{
int mask=1<<i;
result|=(a&mask)xor(b&mask)xor(c&mask);
if(c==0)//carry is 0
{
if((a&mask)&&(b&mask))
c=1;
}
else if(c==1)//carry is 1
{
if(a&mask)||(b&mask)
c=0;
}
}
if(c==0) cout<<"the result is: "<<result<<endl;
else cout<<"overflow"<<endl;
}
Dec 16, 2008
Write a function to add two numbers, without using any arithmetic operator
Write a function to add two numbers, without using any arithmetic operator
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment