Hamming Distance (异或运算)

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.

Note:

0 ≤ x, y < 231.

Example:
Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
The above arrows point to positions where the corresponding bits are different.
解题思路

将两个数分别转换成二进制,然后比较不同的位的个数。

int hammingDistance(int x, int y) {
        int xb = 0, yb = 0, cnt = 0;
        do{
            if(x != 0) { xb = x % 2; x /= 2; } else { xb = 0; }
            if(y != 0) { yb = y % 2; y /= 2; } else { yb = 0; }
            if (xb != yb) cnt++; 
        }while(x !=0 || y != 0);
        return cnt;
}

更直接的方法是使用位运算,异或。

int hammingDistance(int x, int y) {
    int z = x^y;
    int count = 0;
    while (z)
    {
     count += z & 1;
     z >>= 1;
    }
    return count;
}

你可能感兴趣的:(Hamming Distance (异或运算))