1 Star 0 Fork 0

张志光/Leetcode-js

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
461.汉明距离.html 1.02 KB
一键复制 编辑 原始数据 按行查看 历史
zhangzhiguang123 提交于 2019-09-16 19:34 . 力扣
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script>
var hammingDistance = function(x, y) {
let one = x.toString(2); //将x,y转成二进制字符串并分别赋给变量one,two;
let two = y.toString(2);
let num = 0,length = Math.min(one.length,two.length); //length为字符串的最小长度
for(let i= 0;i<length;i++){
if(one.charAt(one.length-i-1) ^ two.charAt(two.length-i-1)) num++; //从两字符串末尾依次往前比较相同位计数
}
let three = one.length>two.length?one:two; //将最长字符串赋给three
for(let i=0;i<Math.abs(one.length-two.length);i++){
if(three.charAt(i)==="1") num++; //从最长字符串首位遍历,如果有1,num++;遍历one.length-two.length次
}
return num;
};
alert(hammingDistance(1,1));
</script>
</body>
</html>
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guangzz/Leetcode-js.git
git@gitee.com:guangzz/Leetcode-js.git
guangzz
Leetcode-js
Leetcode-js
master

搜索帮助