1、Hamming Distance
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.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
class Solution {
public:
int hammingDistance(int x, int y) {
int result=0;
int z;
z=x^y;
while(z){
result++;
z=z&z-1;
}
return result;
}
};
1、x^y得到的z含有的1的位数就是x和y的汉明距离。
2、z&z-1每次会消除一个1,所以循环的次数就是汉明距离。
一点点解释~z的最后一位非0即1
当为0时,设z的最后两位为10,则z-1为01,&后相消,对前面位不影响;当为1时,则z-1为0,&后相消;同理当z的最后三位是100,z-1为011,&后相消,对前面所有位不影响…