Skip to content

Latest commit

 

History

History
34 lines (22 loc) · 1.26 KB

hamming-distance.md

File metadata and controls

34 lines (22 loc) · 1.26 KB
标题 标签
hammingDistance(汉明距离) math,algorithm(数学,算法)

计算两个值之间的汉明距离。

  • 使用 XOR 运算符 (^) 查找两个数字之间的位差。
  • 使用 Number.prototype.toString() 转换为二进制字符串。
  • 使用 String.prototype.match() 计算并返回字符串中 1 的数量。
const hammingDistance = (a, b) =>
  ((a ^ b).toString(2).match(/1/g) || '').length;

ts 代码如下:

调用方式:

hammingDistance(2, 3); // 1

应用场景

以下是一个实战示例:

结果如下:

<iframe src="codes/javascript/html/hamming-distance.html"></iframe>