leetcode 461. Hamming Distance 汉明距离 + 位运算

「爱情、让人受尽委屈。」 2022-06-04 10:27 233阅读 0赞

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.

汉明码,就是位操作

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <cmath>
  14. using namespace std;
  15. class Solution
  16. {
  17. public:
  18. int hammingDistance(int x, int y)
  19. {
  20. int dist = 0, n = x ^ y;
  21. while (n>0)
  22. {
  23. ++dist;
  24. n &= n - 1;
  25. }
  26. return dist;
  27. }
  28. };

发表评论

表情:
评论列表 (有 0 条评论,233人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode 461. 距离

    两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。 给出两个整数 x 和 y,计算它们之间的汉明距离。 注意: 0 ≤ x, y < 231. 利用