NOTE
Hamming Distance
Compute the Hamming distance between two integers using bitwise operations.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Problem Description
The Hamming distance between two integers is the number of positions at which their corresponding binary bits are different.
Given two integers x and y, calculate the Hamming distance between them.
2. Approach
- Approach 1
- XOR: same is 0, different is 1
- AND: for example, to take the 3rd bit, use &0001000
- Approach 2
- XOR directly
- Then count the number of 1s
3. Implementation
3.1. XOR Each Bit
package main
func hammingDistance(x int, y int) int {
bit := 1
count := 0
for i := 0; i < 32; i++ {
numx := x & bit
numy := y & bit
if numx^numy != 0 {
count += 1
}
bit <<= 1
}
return count
}
3.2. Count After XOR
func hammingDistance(x int, y int) int {
res := 0
xor := x ^ y
bit := 1
for i := 0; i < 32; i++ {
if xor & bit != 0 {
res++
}
bit <<= 1
}
return res
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub