Integer Hamming Distance [Solution]
Intuition:
To calculate the Hamming distance between two integers x
and y
,
we need to compare their binary representations bit by bit and count the number of positions where the corresponding bits are different.
We can achieve this by performing bitwise XOR operation between x
and y
to get a number where each bit is set if the corresponding
bits in x
and y
are different.
Then, we count the number of set bits in the result, which gives us the Hamming distance.
Solution:
def int_hamming_distance(x: int, y: int) -> int:
# Perform bitwise XOR operation to get the bits where x and y differ
xor_result = x ^ y
# Initialize the Hamming distance counter
distance = 0
# Count the number of set bits in the XOR result
while xor_result:
# Increment the distance for each set bit
distance += xor_result & 1
# Right shift the XOR result to consider the next bit
xor_result >>= 1
return distance
# Test case
x = 1
y = 4
result = hamming_distance(x, y)
print(result) # Output should be 2
Time Complexity:
The time complexity of this approach is O(1), as we perform a fixed number of iterations (32 iterations for a 32-bit integer) to calculate the Hamming distance.
Space Complexity:
The space complexity is O(1), as we only use a constant amount of additional space for temporary variables and the result.