Skip to main content
Back to problems
#461
Easy Algorithms

Hamming distance

Bit Manipulation
76.6% acceptance
Jan 13, 2026
4025
230
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.

Solution

Rust
Time O(1)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn hamming_distance(x: i32, y: i32) -> i32 {
    (x ^ y).count_ones() as i32
  }
}