Hamming Distance
Description:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integersx
and y
, calculate the Hamming distance.
Note:
0 ≤x
, y
< 2^31.
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.
问题描述:
两个数之间的汉明距离就是求出这两个数字的二进制
中位数
不同的个数。比如上面的1和4,在第0位和第2位数字不同,因此1和4的汉明距离就是2。
Solution:
依据题意可以有一种效率不是那么高的方法:将两个数转换成二进制数,逐位进行比较。
里面会牵扯到类型的转换,会比较麻烦,在这不贴出相应代码。
为了去掉麻烦的类型转换,引入逻辑运算符:异或。
class Solution {
public int hammingDistance(int x, int y) {
int d = 0;
int bitxor = x ^ y;
while (bitxor > 0){
if (bitxor % 2 == 1){
d++;
}
bitxor = bitxor >> 1;
}
return d;
}
}
先将两个数进行异或运算,得到结果,再去数1的个数。
逐位去数1的个数显然不是那么优雅,找了下Java API,找了个专门的函数,代码可简化成如下:
class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}