6.Hamming Distance

Description:

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.

百度了一下汉明距离的定义:对两个字符串进行异或运算,并统计结果为1的个数,那么这个数就是汉明距离。

解题思路:

  直接对x, y进行异或运算,若结果不为0,意味着数字(转换成二进制数值)对应位置的数字不一样,距离加1。随后对运算结果与运算结果减1后的数值进行“与”运算,将对应位置的不同数值置0,重复该过程,直至n=0

代码如下:

class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist=0,n=x^y;
        while(n){
            ++dist;
            n&=n-1;  
        }
        return dist;
    }
};

原文地址:https://www.cnblogs.com/sarahp/p/6686659.html