题目描述:
解:
做法有三种:
暴力的遍历32位统计有几位不一样的(可以先异或,再判断异或后的值每一位是否为0)
class Solution {
public int hammingDistance(int x, int y) {
int ret = 0;
int tmp = x ^ y;
for(int i=0; i<32; i++) {
ret += (tmp & 1) == 0 ? 0 : 1;
tmp >>= 1;
}
return ret;
}
}
通过
x & (x - 1)
直接获取二进制位中最右边1的性质优化class Solution {
public int hammingDistance(int x, int y) {
int ret = 0;
int tmp = x ^ y;
while (tmp != 0) {
tmp = tmp & (tmp - 1);
ret ++;
}
return ret;
}
}
使用语言自带的功能函数。
class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}