Skip to content

Files

Latest commit

 

History

History
28 lines (19 loc) · 1 KB

hammingDistance.md

File metadata and controls

28 lines (19 loc) · 1 KB
标题 标签
hammingDistance(汉明距离) math,algorithm(数学,算法)

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

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

调用方式:

hammingDistance(2, 3); // 1

应用场景

结果如下:

<iframe src="codes/javascript/html/hammingDistance.html"></iframe>