Short C++ solution using bit manipulation. [AC]


  • 0
    S

    Xor returns sets the bit 1 where the bit in the corresponding elements are different. Using this we first use xor and then count the set bits.

    public:
        int hammingDistance(int x, int y) {
            // this will give us different bits
            int n = x^y;
            // we just need to count the number of set bits now.
            unsigned int count = 0;
            // the number of times the loop runs is our result
            // if we subtract 1 from a number and do & operation we unset the righmost bit.
            while(n)
            {
                n = n&(n-1);
                count++;
            }
            return count;
        }
    };
    

Log in to reply
 

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