题目:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/26/others/65/
题目描述:
汉明距离
两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x
和 y
,计算它们之间的汉明距离。
注意:
0 ≤ x
, y
< 231.
示例:
输入: x = 1, y = 4
输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
上面的箭头指出了对应二进制位不同的位置。
思路:可以对X 和Y进行异或运算 得到temp 。然后计算temp 位为1 的个数。这里还利用了temp=temp&temp-1 的技巧 统计位为1的个数。比如: temp =1011 temp-1 = 1010 , temp&temp-1 = 1010 count +1 ;
temp = 1010 temp-1 = 1001 , temp&temp-1 = 1000 count+1;
temp = 1000 temp -1 = 0111 , temp&temp-1 =0000 count +1; temp =0 结束。刚好count 为 temp位为1的个数
代码:
class Solution {
public int hammingDistance(int x, int y) {
int res = 0;
int temp = x ^ y;
while (temp!= 0) {
res ++;
temp &= (temp - 1);
}
return res;
}
//另外的方法
public int hammingDistance3(int x, int y) {
int res = 0;
String s1 = Integer.toBinaryString(x);
String s2 = Integer.toBinaryString(y);
int len1 = s1.length();
int len2 = s2.length();
while (len1 > len2) {
s2 = "0" + s2;
len2++;
}
while (len1 < len2) {
s1 = "0" + s1;
len1++;
}
char[] a = s1.toCharArray();
char[] b = s2.toCharArray();
for (int i = 0; i < len1; i++) {
if (a[i] != b[i]) {
res++;
}
}
return res;
}
public static void main(String[] args) {
System.out.println(hammingDistance1(7,8));
}
}