LeetCode 461: Hamming Distance

来源:互联网 发布:贝克曼梁法弯沉数据 编辑:程序博客网 时间:2024/06/11 04:46

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 = 4Output: 2Explanation: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++的时候学的比较粗略,之后也没怎么练习。