Leetcode 461. Hamming Distance
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.
x and y?
x and y are integers, 0 ≤ x, y < 2^31.x and y.^) operation on x and y. This will give a number that has bits set to 1 wherever the bits of x and y are different.Here’s how you can implement this:
public class HammingDistance {
public int hammingDistance(int x, int y) {
int xorResult = x ^ y;
return Integer.bitCount(xorResult);
}
public static void main(String[] args) {
HammingDistance hd = new HammingDistance();
// Example usage:
System.out.println(hd.hammingDistance(1, 4)); // Output: 2
}
}
x ^ y:
a and b, a ^ b is 1 if a is different from b, else it is 0.x = 1 (binary 0001)y = 4 (binary 0100)x ^ y gives 0101 (binary) which is 5.Integer.bitCount(5) counts the number of 1s in the binary representation of 5 (binary 0101). There are two 1s.2.Integer.bitCount() also runs in constant time, O(1).Thus, the overall time complexity is O(1).
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?