XOR has a value of 1 only when 2 bits are different:
XOR
a b a ^ b
-------------
0 0 0
0 1 1
1 0 1
1 1 0
- Use XOR as
x ^ y
- The number of bits set as
1
inx ^ y
is our solution
class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
- Time Complexity: O(1)
- Space Complexity: O(1)