LeetCode_461. Hamming Distance

/*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.*/

题目的意思是:找到x和y的二进制位中,不相同的个数;

自己的思路的先将x,y转化为二进制存储,然后比较,结果超时了:

var hammingDistance = function(x, y) {
    var MAX = Math.pow(2, 32);
  if (x < 0 || y < 0 || x > MAX || y > MAX) {
        console.log("max");
        return false
    }
    var arr1 = revertTobit(x);
    var arr2 = revertTobit(y);
    while (arr1.length != arr2.length) {
        if (arr1.length < arr2.length) {
            arr1.unshift(0);
        } else {
            arr2.unshift(0)
        }
    }
    var count = 0;
    for (var i = 0; i < arr1.length; i++) {
        if (arr1[i] != arr2[i]) {
            count++;
        }
    }
    return count;
};

/*将一个数转换为二进制数组存储*/
var revertTobit = function(x) {
    var arr = [];
    while (x != 1) {
        var bit = x % 2;
        x = Math.floor(x / 2);
        arr.unshift(bit);
    }
    arr.unshift(1);
    return arr;
}

正确的方法是采用位运算,x异或y 得到的z

关键在于计算z有多少个1,方法:
用z和z-1与运算;这样做的与运算每次都把最右边的1变为0,最后直到z为0;

var hammingDistance = function(x, y) {
  var count = 0;
  var n = x ^ y;
  while (n) {
    ++count;
    n = (n - 1) & n;
  }
  return count;
};
点赞