We just need to XOR given 2 integers and count number of '1' bits in the result.


  • 0
    G
    public int hammingDistance(int x, int y) {
            int xor = x ^ y;
            int count = 0;
            while(xor != 0) {
                xor = xor & (xor - 1);
                ++count;
            }
            
            return count;
        }
    

Log in to reply
 

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