LeetCode 461: Hamming Distance

LeetCode 461: Hamming Distance

题目大意

求两个整型数x,y的汉明距离。

Description

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.

给定代码

int hammingDistance(int x, int y) {

}

思路分析&相应代码

  • 我的初级版

根据上面的例子可知,我们需要判断两个数值二进制为有多少位不同,所以可以直接根据十进制向二进制的转换过程而获得结果。需要注意的是必须两个数都为0时才能判断停止。

int hammingDistance(int x, int y) {
        int count = 0;
        while(x!=0 || y!=0){
            if(x%2 != y%2){
                count++;
            }
            x/=2; y/=2;
        }
        return count;
    }
  • Solution中的升级版
    思路:先将两个数进行按位异或,然后判断异或获得的结果中有几个1。
int hammingDistance(int x, int y) {
        int dist = 0, n = x ^ y;
        while (n) {
            ++dist;
            n &= n - 1;
        }
        return dist;
    }

分析总结

难得首次提交就AC,虽然自己调试的时候还是有错误。Solution中还有大神只用了一行代码,也是666。私以为,我的方法是最笨的,当然也是我这种菜鸟最容易想到的,上面那种方法对于我来说的问题在于,对于位运算不够熟悉,所有完全想不到还可以那样来按位异或甚至获得二进制中1的个数,当时学C++的时候学的比较粗略,之后也没怎么练习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值