leetcode7:汉明距离
1题目
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.
汉明距离是两个字符串对应位置的不同字符的个数,这里指二进制的不同位置
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去掉算出长度
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.