Approach #1
Intuition
Since we need to identify the number of positions at which the corresponding bits are different, the first thought would be to XOR both the numbers.
XOR of two bits is 1 only if both the numbers are different.
0^1 = 1
1^0 = 1
0^0 = 0
1^1 = 0
Algorithm
Return the count of set bits in XOR of two given numbers
Java
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x^y);
}
}
Complexity Analysis

Time complexity : The run time depends on the number of bits in $$n$$ where $$n$$ is the binary representation of $$x$$ or $$y$$. Because $$n$$ in this piece of code is a 32bit integer, the time complexity is $$O(1)$$

Space complexity : The space complexity is $$O(1)$$, since no additional space is allocated