leetcode7:汉明距离

1题目

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.less

Given two integers x and y, calculate the Hamming distance.
汉明距离是两个字符串对应位置的不一样字符的个数,这里指二进制的不一样位置code

2.例子

Input: x = 1, y = 4

Output: 2

Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

3. 个人解法

var hammingDistance = function(x, y) {
   return (x^y).toString(2).replace(/0/g, "").length
};

先将X,y进行异位或运算再转化成二进制而后把0去掉算出长度ip

Runtime: 76 ms, faster than 18.42% of JavaScript online submissions for Hamming Distance.
Memory Usage: 33.8 MB, less than 40.96% of JavaScript online submissions for Hamming Distance.

4. 其余方法

var hammingDistance = function(x, y) {
  let ones = 0;
  let z = x ^ y;
    
  while (z) {
    if (z & 1) {
      ones += 1;  
    }
    
    z = z >> 1;
  }
  
  return ones;
};

先算出不一样位数,而后用右移运算符算出能右移几回来获取距离字符串

Runtime: 60 ms, faster than 89.17% of JavaScript online submissions for Hamming Distance. Memory Usage: 34 MB, less than 6.03% of JavaScript online submissions for Hamming Distance.