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.

int hammingDistance(int x, int y) 
{
    int cnt = 0;
    int result = x^y;
    
    while(result)
    {
        if(result &1)
            cnt++;
        result >>= 1;
    }
    return cnt;
    
}

经验教训

这道题是求两个数对应的二进制位有几位不同,开始对题目理解错误,以为是求异或之后前后两个1相差几位,看给的例子验证,结果一个简单的问题写了半小时还没AC,google搜了题目之后才发现原来自己理解有误。