https://leetcode.com/problems/hamming-distance/description/
bit manipulation
one tip: (n & n - 1) is to remove the 1 in the LSB.
用这个方法比comment的方法快一丢丢,毕竟少了一个if
class Solution {
public:
int hammingDistance(int x, int y) {
return countOne(x^y);
}
int countOne(int n)
{
int count = 0;
while(n)
{
//if(n & 0x1 == 0x1)
{
count++;
}
//n = n >> 1;
n &= n - 1;
}
return count;
}
};