> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Hamming Distance Python Solution with Tests

> Tested Python solution for LeetCode 461 with 20 pytest cases. Generate a practice environment with lcpy.

LeetCode 461, [Easy](/catalog/easy). Topics: [Bit Manipulation](/catalog/topics/bit-manipulation). [View on LeetCode](https://leetcode.com/problems/hamming-distance/description/).

Generate this problem as a practice environment: tested reference solution, 20 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 461   # by problem number
lcpy gen -s hamming_distance   # by problem name
```

## Problem

The \<a href="[https://en.wikipedia.org/wiki/Hamming\_distance](https://en.wikipedia.org/wiki/Hamming_distance)" target="\_blank">Hamming distance\</a> between two integers is the number of positions at which the corresponding bits are different.

Given two integers \<code>x\</code> and \<code>y\</code>, return \<em>the \<strong>Hamming distance\</strong> between them\</em>.

### Examples

```
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.
```

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

### Constraints

* 0 \<= x, y \<= 2^31 - 1

**Note:** This question is the same as [2220: Minimum Bit Flips to Convert Number](https://leetcode.com/problems/minimum-bit-flips-to-convert-number/description/).

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/hamming_distance/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/hamming_distance/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(b), b = number of differing bits (<= 31)
    # Space: O(1)
    def hamming_distance(self, x: int, y: int) -> int:
        return (x ^ y).bit_count()
```

## Complexity

| Time | Space |
| - | - |
| O(b), b = number of differing bits (\<= 31) | O(1) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.