LeetCode 461. Hamming Distance (C++)

题目:

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 ≤ xy < 2^31.

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.

分析:

将两个数的二进制进行比较,不同的计数加一,最后返回总数。

由于1&1 = 1,1&0 = 0,可以分别将x,y和1做与运算得到x,y的最后一位的值,再做异或运算,然后再将x,y右移一位。因为题里限定了x,y大小,所以只32次循环就够了。

程序:

class Solution {
public:
    int hammingDistance(int x, int y) {
        int nums = 0;
        for (int i = 0; i < 32; i++){
            if ((x & 1) ^ (y & 1))
                nums++;
            x = x >> 1;
            y = y >> 1;
        }
        return nums;
    }
};
原文地址:https://www.cnblogs.com/silentteller/p/10705303.html