您的位置:首页 > 编程语言 > Java开发

leetcode-461 Hamming Distance

2017-03-27 18:32 435 查看
英文

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

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.

中文

汉明距离:任意两个整数,转换为二进制,计算相同位数中,不相同数字的数量,即同一位置,一个位0,一个位1,那么这就是相同位数数字不相同,距离加1

3. 说明

因为是计算相同位数数字不相同的个数,想到了位运算的^(异或运算)运算,两者不相同为1,这样两个整数进行异或运算后,不相同的位数都是1,那么就转换为求一个数的二进制中1的个数

4. java代码

public class HammingDistance {
public static void main(String[] args) {
System.out.println(hammingDistance(1,4));
}
public static int hammingDistance(int x,int y){
int distance=0;
int temp = x^y;
while(temp>0){
if((temp^1)<temp){
distance++;
}
temp >>=1;
}
return distance;
}
}


上述代码:两个整数异或运算后,通过与1再次异或,因为1与1进行异或运算后为0,因此与1的异或运算值小于原值,通过这样判断1的个数。后来通过查询获取更优的运算,代码如下:

public class HammingDistance {
public static void main(String[] args) {
System.out.println(hammingDistance2(1,4));
}
public static int hammingDistance2(int x,int y){
int distance=0;
int temp = x^y;
int count=0;
while(temp>0){
distance++;
temp &= (temp - 1);
count++;
}
System.out.println("2:"+count);
return distance;

}
}


代码说明:方法一中,需要每个位数都需要判断,而方法二中位的跨度比较大,只比较为1的位数,减少了比较次数

5. 备注

如果有更优的计算方法,请留言
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode-java