1 解题思想
这道题就是求两个数的海明距离,而海明距离也就是两个数对应的二进制bit位里不同的位数
所以这道题直接异或就可以,异或时,二者相同为0,不同为1,异或完后统计为1的位数就好
2 原题
he 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.
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.
3 AC解
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}