Problem:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x
and y
, calculate the Hamming distance.
题目:求汉明距离,即两个数不同位数的数量
思路:本来是想每比较一位,同时再x,y右移一位,判断依据为异或后是否为1.
方法第一遍没通过,再看到异或后,又想到先将两个数异或,再看二进制中为1位的数量即可。
代码:
class Solution {
public int hammingDistance(int x, int y) {
int ret = 0;
int z = x ^ y;
while(z!=0){
if((z&1)==1)
ret++;
z>>=1;
}
return ret;
}
}