Hamming Distance

Easy Bit Manipulation

Problem

The Hamming distance between two integers is the number of positions where their bits differ. Return the Hamming distance between x and y.

Example 1 Input: x = 1, y = 4 Output: 2
Example 2 Input: x = 3, y = 1 Output: 1

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def hammingDistance(self, x, y):
        return bin(x ^ y).count('1')

Java

class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Hamming Distance interactively → ← All solutions