Hello_Motty

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

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 ≤ xy < 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.

题意:找到两个数的汉明距离,即两个数转换成二进制后有多少位不相同。
基本思路:
两数直接按位异或,如某一位两数相同则为0,反之为1。然后变成了数异或结果有多少个1。查1的方法有很多,这里不是重点留到后面再说,这里面先使用一种
最原始的。这道题没有复杂的内存分配,所以用c和c++写法是类似的,所以写了c。
 1 int hammingDistance(int x, int y) {
 2     int z = x ^ y;
 3     int cnt = 0;
 4     for( ; z > 0; )
 5     {
 6         if(z%2 == 1)//除2余数为1,就在统计结果上加1,这里是最通俗的想法,并不是最简洁写法
 7             cnt++;
 8         z /=2 ;//将z除2 ,统计下一位是否为1
 9     }
10     return cnt;
11 }

以上就是这道简单难度通过率最高的题的思路,运行时间3ms。

附上我写的最简写法。

1 int hammingDistance(int x, int y) {
2     int z = x ^ y,cnt=0;
3     for(int i=0;i<32;i++) cnt+=(z>>i)&1;
4     return cnt;
5 }

 



posted on 2017-08-07 23:01  Hello_Motty  阅读(109)  评论(0编辑  收藏  举报