LeetCode #461: Hamming Distance

Problem

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 < 2^31.

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.

Solution

  1. Hamming Distance的定义:任意两个数字对应的二进制数,如1的二进制表示是0001,4的二进制表示是0100,对于1和4来说,它们的二进制表示中对应的位有两位不同(1的最低位是1,4的最低位是0;1的第三位是0,4的第三位是1),所以它们的Hamming Distance = 2。

  2. 既然涉及到位数的异同,自然就想到了异或运算。

    • A异或B = (~A)B + A(~B)
    • 在C++中,异或运算符是^
      例如:z = x ^ y;
  3. z = x ^ y,再求出z中1的数量,这个数量就是要求的Hamming Distance.

Code (C++)

Version 1
class Solution {
public:
    int hammingDistance(int x, int y) {
        int z = x ^ y; //求x和y的异或
        int count = 0;
        for (; z; count++){
            //逐个清除z最右边的1
            //循环的终止条件是z==0
            z &= z - 1; 
        }

        return count;
    }
};

Note: 对z &= z - 1的解释
举两个例子:
1. 6(0110)和7(0111),6 & 7 = 0110,消去了7最右边的1
2. 7(0111)和8(1000),7 & 8 = 0000,消去了8最右边的1
总的来说就是,z - 1是从z的最右边减去1,求 z & (z - 1)可以消去z最右边的1.
在这道题中,消去多少个1,就意味着x和y的Hamming Distance有多大。

Version 2

第二个版本的思路就比较正常,老老实实求z中1的位数。
可以通过从最低位开始逐位和1进行与运算:
1. 结果是1说明z的该位是1,计数器+1,然后将z右移1位
2. 结果是0说明z的该位是零,计数器不变,z右移1位。

class Solution {
public:
    int hammingDistance(int x, int y) {
        int z = x ^ y;
        int count = 0;
        for (; z; z >>= 1){
            if (z & 1) 
                count++;
        }

        return count;
    }
};

Summary

  1. 了解了Hamming Distance的定义。
  2. 了解了C++中的移位运算(<<和>>)、与运算(&)、异或运算(^)
  3. 虽然这道题是LeetCode上AC率最高的一道题,但是依然有一定难度,考察了之前很少涉及的位运算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值