461. Hamming Distance

来源:互联网 发布:阻止电脑自动安装软件 编辑:程序博客网 时间:2024/05/21 19:27

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 = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different. 
我的解答:

class Solution {public:    int hammingDistance(int x, int y) {        int r = x ^ y;        int sum = 0;        for(int i = 0; i < 8 * sizeof(int); ++i){            int ret = r & (0x1 << i);            if(ret){                sum++;            }        }        return sum;    }};
在leetcode上看到一个解答:

class Solution {public:    int hammingDistance(int x, int y) {        int dist = 0, n = x ^ y;        while (n) {            ++dist;            n &= n - 1;        }        return dist;    }};
注意其中有一个式子: n &= n - 1

看一个例子    n = 100100        n - 1 = 100011

可以看到  n & n - 1 的效果式将n中最后一个1给消掉。这样计算异或后的1的个数的时间复杂度对于1比较少的数字来说比遍历要快不少。

那么看看利用这个性质还可以解决哪些问题。

1.判断n是否是2的幂,或0

   如果是2的幂的话,那么其2进制数中只有1位为1,那么如果n不为0且n & n - 1 = 0,则n为2的幂

2.如本题中计算二进制数中1的个数


原创粉丝点击