Java Bitwise Solution 10ms


  • 0
    C

    First of all we use XOR bitwise operator to get binary number, which contains 1 in positions, where difference was found.

    For 1 (0001) and 4 (0100) XOR operation gives us 5 (0101).

    Now we see that result contains two 1's.
    Next step is to count these 1's.

    I want to remind that last bit of even numbers always equals to 0, and odd ones - 1.

    So we check whether result of XOR operation is odd and increment the counter by one. After that, perform signed right shift of XOR operation result by one bit. Keep doing it while result is greater than 0.

    class Solution {
        public int hammingDistance(int x, int y) {
            int xorRes = x ^ y;
            int distance = 0;
    
            while (xorRes > 0) {
                if ((xorRes & 1) > 0)
                    distance++;
    
                xorRes >>= 1;
            }
            
            return distance;
        }
    }
    

Log in to reply
 

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