The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x
and y
, calculate the Hamming distance.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (in binary) = 0001
4 (in binary) = 0100
The positions where the bits are different are 1 and 3. Therefore, the Hamming distance is 2.
x
and y
?
x
and y
will be non-negative and fit within the typical integer range.x
and y
are integers.With this information, we can proceed to the strategy for the solution.
x
and y
. The XOR operation will yield a number where the bits set to 1
represent the positions where the bits of x
and y
differ.1
s. This count represents the Hamming distance.def hammingDistance(x: int, y: int) -> int:
# Perform XOR to get differing bits
xor_result = x ^ y
# Convert to binary string and count '1's
distance = bin(xor_result).count('1')
return distance
O(1)
1
s in the result (which involves a fixed number of bits for integers) both take constant time. Python handles integers with a fixed bit-length, making the operations effectively O(1)
.This completes the solution.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?