[LeetCode] 461.Hamming Distance 备忘

来源:互联网 发布:unity3d 2d地图 编辑:程序博客网 时间:2024/06/08 03:38

461. Hamming Distance

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 < 231.

Example:

Input: x = 1, y = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ?   ?The above arrows point to positions where the corresponding bits are different.

求两个整数之间对应的位上,不相同的位有多少个。


由于题目中对于x,y限制了大小,所以最简单的方法,就是2个数字异或之后做右位移运算,判断每一个位置是否为1,进行计数,直到右移次数到达31次为止。

class Solution {public:    int hammingDistance(int x, int y) {        int n = x ^ y;        int i = 0;        int distance = 0;        do        {            if (n & 1 == 1)            {                ++distance;            }            n >>= 1;            ++i;        }while (i < 31);                return distance;    }};


有一种更巧妙的方法,也是将2个数字异或之后的结果进行遍历。假设2个数字异或的结果是n,遍历条件是n不为0,在遍历中首先递增计数的值,然后对n进行操作 n &= (n - 1);这一步的目的是每次在递增计数完之后关闭n最右边一位值为1的位(即置为0),直到跳出循环,即可计算2个数之间具有不同值的位的个数。

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



原创粉丝点击