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.
Note:
0 ≤ x
, y
< 231.
int hammingDistance(int x, int y) {
int res = 0;
for(int i = 0; i < 31; i++){
if((x&(1<<i))^(y&(1<<i)))res++;
}
return res;
}