思路:求两个数的异或,再统计1的个数就行。
class Solution {
public int hammingDistance(int x, int y) {
int tmp = x ^ y;
int distance = 0;
while (tmp != 0) {
if ((tmp & 1) == 1) {//或者tmp%2 == 1
distance++;
}
tmp = tmp >>> 1;//注意>>> >>的区别
}
return distance;
}
}