两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。
给你两个整数 x 和 y,计算并返回它们之间的汉明距离。
示例 1:
输入:x = 1, y = 4
输出:2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
上面的箭头指出了对应二进制位不同的位置。
示例 2:
输入:x = 3, y = 1
输出:1
提示:
0 <= x, y <= 2$31$ - 1
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/hamming-distance
使用异或的方式:
class Solution {
public int hammingDistance(int x, int y) {
//如果两个值相等,则汉明距离为0
if(x == y){
return 0;
}
//计算得到异或的结果,也就是z的二进制中的1的个数,就是其对应的汉明距离
int z = x ^ y;
int count = 0;
while(z != 0){
count += z & 1;
z = z >> 1;
}
return count;
}
}
时间复杂度:O(log(C)) C 表示是n的二进制位数
不使用异或的方式:
class Solution {
public int hammingDistance(int x, int y) {
//如果两个值相等,则汉明距离为0
if(x == y){
return 0;
}
int count = 0;
while(x != 0 || y != 0){
if((x&1) != (y&1)){
count++;
}
x=x>>1;
y=y>>1;
}
return count;
}
}
使用工具类:(一般情况下工具类记不住,还是掌握前面两种比较实惠)
class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
来自官方:Brian Kernighan 算法
(n & (n - 1)可以把最右边的1变为0)!!!!!
class Solution {
public int hammingDistance(int x, int y) {
//如果两个值相等,则汉明距离为0
if(x == y){
return 0;
}
int z = x ^ y;
int count = 0;
while(z != 0){
z = z&(z-1); // n 同 n-1做与运算是为了消除最右边的1
count++;
}
return count;
}
}