webVueBlog / LeetCode-HOT-100

力扣 (LeetCode) 🔥LeetCode HOT 100

Home Page:https://webvueblog.github.io/LeetCode-HOT-100/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

461. 汉明距离

webVueBlog opened this issue · comments

461. 汉明距离

Description

Difficulty: 简单

Related Topics: 位运算

两个整数之间的 指的是这两个数字对应二进制位不同的位置的数目。

给你两个整数 xy,计算并返回它们之间的汉明距离。

示例 1:

输入:x = 1, y = 4
输出:2
解释:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
上面的箭头指出了对应二进制位不同的位置。

示例 2:

输入:x = 3, y = 1
输出:1

提示:

  • 0 <= x, y <= 231 - 1

Solution

Language: JavaScript

/**
 * @param {number} x
 * @param {number} y
 * @return {number}
 */
var hammingDistance = function(x, y) {
    return (x^y).toString(2).split('').filter(i => i === '1').length
};