码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 461. Hamming Distance

时间:2017-03-30 00:46:14      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:different   target   cal   min   代码   lan   console   osi   需要   

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的个数思路是:与1进行安慰与,如果所得结果为1,那么证实二进制位为1. 然后将结果右移一位继续循环,直到结果为0为止。
代码如下:
function hanming(x, y) {
    var num = x ^ y;
    var result = 0;
    while ( num > 0) {
        if(num & 1) {
            result++;
        }
        num = num >> 1;
    }
    return result;    

}
var a  = hanming(1,4);
console.log(a);

 

LeetCode 461. Hamming Distance

标签:different   target   cal   min   代码   lan   console   osi   需要   

原文地址:http://www.cnblogs.com/gogolee/p/6642206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!