Thursday, September 20, 2018

Method to find XOR of two numbers without using XOR operator

I need to find an optimized solution for this interview question. When I mention optimized, it should be truly optimized without over complicating the code.
For the time being, I have written down a not-so optimized code. This will require further testing.


#include <stdio.h>
unsigned int find_xor(unsigned int a,unsigned int b);
int main()
{
    int a, b,c;
    scanf("%d %d", &a,&b);
    c = find_xor((unsigned int)a,(unsigned int)b);
    printf("The xor is %x",c);
    //get(c);
    return 0;
}

unsigned int find_xor(unsigned int a,unsigned int b)
{
 unsigned int c = 0, i=0,d = 0;
 unsigned int a1,b1;
  printf("The a %x b %x \n",a,b);
 while ( (a || b) && (i<32))
 {
     a1 = a &1;
     b1 = b &1;
     printf("The a1 %x b1 %x \n",a1,b1);
     if((a1 != b1)) {
      c = (c<<1)|(1);
      printf("The c %x  \n",c);
     }

     i++;
     a = a>>1;
     b= b>>1;
  }
  //the bits are reverse
   printf("The xor is %x",c);
     while (c) {
         d = (d<<1) |(c & 0x1);
         c = c>>1;
        
     }
 c = d;
 return c;
   
}