Hamming Distance Solution

  • 0

    Let me start with problem understanding first , basically we want to see what is not common between bits of two numbers or character. we can find those using bit wise operation
    Bitwise And operation will come in Handy here.

    1. if we AND1 with 1 then the out put will be 1.
    2. if we AND 1 with 0 then output will be 0. so we take advantage of that and compare if both the numbers bits And with 1 are not same and if it is not then we have different bits set and increment the counter.

    Recursive implement ion is given below.

    int hammingDistance(int x, int y) {
        int i=0;
        int count = 0;
        if((x == 0 && y ==0)) return 0;
        printf("%d %d \n",x,y);
        if((x  & 1 << i)  != (y & 1 << i))
              count ++;       
           count = count + hammingDistance(x >> 1, y >> 1);
       return count; 

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.