Skip to content

Latest commit

 

History

History
72 lines (56 loc) · 1.01 KB

461.汉明距离.md

File metadata and controls

72 lines (56 loc) · 1.01 KB

461. 汉明距离

url

题目

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

给出两个整数 xy,计算它们之间的汉明距离。

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

方法

排序+贪心

code

js

let hammingDistance = (x, y) => {
    let z = x ^ y;
    let cnt = 0;
    while (z !== 0) {
        z &= (z - 1);
        cnt++;
    }
    return cnt;
};
console.log(hammingDistance(1, 4));

go

func hammingDistance(x int, y int) int {
	z := x ^ y
	cnt := 0
	for z != 0 {
		z &= z - 1
		cnt++
	}
	return cnt
}

java

class Solution {
    public int hammingDistance(int x, int y) {
        int z = x ^ y;
        int cnt = 0;
        while (z != 0) {
            z &= (z - 1);
            cnt++;
        }
        return cnt;
    }
}