Java Solution using Basic Bitwise Shifts O(n)


  • 0
    B

    Explanation
    My solution is to repeatedly compare the bits of both x and y in sync starting from the right-most bit, while updating a counter variable. Once we've finished, we return our counter.

    Time Complexity
    The running time is O(n) where n = max(# bits in x, # bits in y).

    class Solution {
        public int hammingDistance(int x, int y) {
            int count = 0;
            while (x != 0 || y != 0) {
                // Check if the right-most bits are equal 
                if (x % 2 != y % 2) {
                    count++;
                }
                x = x >> 1;
                y = y >> 1;
            }
            return count;
        }
    }
    

Log in to reply
 

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