Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Example 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
          ↑     ↑
The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1
Output: 1

Constraints:

  • 0 <= x, y <= 231 - 1

My Solution

We can solve this problem by XOR-ing x and y together and then counting the number of set bits in the result.

Time complexity would be O(1) because it only requires a constant 31 iterations. Space complexity also would be O(1) since it only requires constant extra space.

class Solution {
    public int hammingDistance(int x, int y) {
        int num = x ^ y;
        int out = 0;

        while (num > 0) {
            out += (num & 1);
            num >>= 1;
        }

        return out;
    }
}
Previous
Previous

Island Perimeter

Next
Next

Find Missing Elements