计算两个值之间的汉明距离。
使用XOR运算符( ^
)查找这两个数字之间的位差,使用 toString(2)
转换为二进制字符串。使用 match(/1/g)
计算并返回字符串中 1
的数量。
const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
hammingDistance(2, 3); // 1
注:在信息论中,两个等长字符串之间的汉明距离(英语:Hamming distance)是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。- 维基百科
更多代码 JavaScript 实用代码片段 请查看 https://www.html.cn/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂