461. Hamming Distance

xiaoxiao2021-02-28  86

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. 我的解答:

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的个数

转载请注明原文地址: https://www.6miu.com/read-53816.html

最新回复(0)