C 0ms easy to understand

  • 0
    int hammingDistance(int x, int y) {
        int z = x ^ y;
        int hamCount = 0;
        int counter = 0;
        for (counter; counter < 32; counter++) {
            if ((z | 1) == z) hamCount++;
            z = z >> 1;
        return hamCount;

    Problem states that x,y are < 2^31, implying the use of 32-bit int architecture.

    if a number OR'd with 1 is the same number, that means the rightmost bit must have been a 1. In this manner of detection and shifting off the rightmost bit, we can count the number of "1" bits in the XOR result.

    The XOR identifies the bit differences

Log in to reply

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