
解法
异或运算,计算完以后再算计算结果中有几个1,就是不同的二进制数。
class Solution {
public int hammingDistance(int x, int y) {
int s = x ^ y;
int ret = 0;
while (s > 0) {
ret += s & 1;
s >>= 1;
}
return ret;
}
}
更快的算1的方法
class Solution {
public int hammingDistance(int x, int y) {
// 异或算出不同位的结果
int s = x ^ y;
int ret = 0;
while (s > 0) {
// 去掉二进制中最右边的值
s &= s - 1;
ret++;
}
return ret;
}
}
网友评论