将xy求异或,统计结果中位数为1的个数。
1.判断n最低位是否为1,然后右移一位。
2.n&(n-1)可以实现将n的最低位的1变成0。
class Solution {
public int hammingDistance(int x, int y) {
int out = x ^ y;
int count = 0;
while(out > 0){
if((out & 1) == 1){
count ++;
}
out >>= 1;
}
return count;
}
}
class Solution {
public int hammingDistance(int x, int y) {
int count=0;
int n=x^y;
while(n!=0){
count++;
n=n&(n-1);
}
return count;
}
}