C non-looping solution using parallel algorithm


  • 0
    D

    The idea is to XOR the two numbers so that the number of set bits is equal to the Hamming Distance, from there count the number of bits to get the Hamming distance.

        x = x^y;
        x = x - ((x>>1) & 0x55555555);
        x = (x & 0x33333333) + ((x>>2) & 0x33333333);
        return ((((x + (x>>4)) & 0x0F0F0F0F) * 0x01010101)>>24);
    

    The last three lines use what is known as 'parallel algorithm' or 'variable-precision SWAR algorithm' to count the number of bits in the result of your XOR.


Log in to reply
 

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