Time spent here:

Tuesday, 22 December 2015

Find XOR of two number without using XOR operator

Simple Solution is to traverse all bits one by one. For every pair of bits, check if both are same, set the corresponding bit as 0 in output, otherwise set as 1.
SOLUTION IN C++
#include <iostream>
using namespace std;

int main()
{
   int x,y,b1,b2,i;
   int res=0,ans=0;
   cin>>x>>y;
   for(i=31;i>=0;i--)
   {
       bool b1=x & (1 << i);
       bool b2=y & (1 << i);
       bool x_y = (b1 & b2) ? 0 : (b1 | b2);  
        res <<= 1;
        res |= x_y;
    
   }
  cout<<"xor is "<<res;
    return 0;
}
OUTPUT:

No comments:

Post a Comment