您的位置:首页 > 其它

LeetCode-461. Hamming Distance

2017-01-20 10:31 387 查看
The 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.

思路:算两个数二进制按位比较不同位的个数,先异或,再求xor的二进制1的个数。

public class Solution {
public int hammingDistance(int x, int y) {
int xor = x ^ y;
int distance = 0;
while (xor != 0) {
distance ++;
xor &= (xor-1); //清除xor最右边的1
}
return distance;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: