1、我的解法(C++)
3、一行代码(Java)
class Solution {
public:
int hammingDistance(int x, int y) {
int a = x^y;
int num=0;
while(a>=1){
if(a%2==1) num++;
a/=2;
}
return num;
}
};
思路:按位异或操作之后,求两个数不同的位上为1。
2、其他解法(C++)
class Solution {
public:
int hammingDistance(int x, int y) {
int dist = 0, n = x ^ y;
while (n) {
++dist;
n &= n - 1;
}
return dist;
}
};
3、一行代码(Java)
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}