LeetCode:461. Hamming Distance 汉明距离

深藏阁楼爱情的钟 2021-06-24 16:10 750阅读 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,然后使用n&(n-1)的方式可以每次除掉n二进制上的最后一位1。

  1. class Solution {
  2. public int hammingDistance(int x, int y) {
  3. x = x^y;
  4. y = 0;
  5. while(x!=0){
  6. y++;
  7. x &= (x-1);
  8. }
  9. return y;
  10. }
  11. }

发表评论

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

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

相关阅读

    相关 LeetCode 461. 距离

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