Description The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 0 ≤ x, y < 2’31. Given two integers x and y, calculate the Hamming distance.
Example Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different.
Solution
public int hammingDistance(int x, int y) {
intdistance = 0;
int temp = x ^ y;// 获取两个二进制数的不同位数的值;while (temp != 0) {
distance++;
temp = temp & (temp - 1);//计算一个二进制数中含1的个数
}
System.out.println(distance);
returndistance;
}