Short and straight C++ code


  • 0
    G
        int hammingDistance(int x, int y) {
            int z = x ^ y;    // XOR will only have those bits set where x and y bits differ
            int cnt = 0;
            while (z != 0) {
                cnt++;
                z &= (z - 1);    // The usual trick to find the number of set bits
            }
            return cnt;
        }
    

Log in to reply
 

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