美文网首页
Leetcode 461. Hamming Distance

Leetcode 461. Hamming Distance

作者: raphah | 来源:发表于2017-05-19 13:06 被阅读157次

leetcode

461. Hamming Distance

TheHamming distancebetween two integers is the number of positions at which the corresponding bits are different.

Given two integersxandy, calculate the Hamming distance.

Note:

0 ≤x,y< 231.

Example:

Input:x = 1, y = 4

Output:2

Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different.

使用python语言编写

参见维基百科:

海(汉)明距离:在信息论中,两个等长字符串之间的汉明距离(英语:Hamming distance)是两个字符串对应位置的不同字符的个数。换句话说,它就是将一个字符串变换成另外一个字符串所需要替换的字符个数。

应用领域:汉明重量分析在包括信息论、编码理论、密码学等领域都有应用

实际应用:谷歌文本去重计算时,就使用到了海明距离。爬虫在对内容去重时也可用到该方法。

1.使用最原始的方法直接写

①将十进制转为二进制,转换后为0bxxxx,去除0b。

②通过判断将长度短的数,前面用0补齐。

③使用for循环对比每一位,不同的进行累加。

关键:str1 = bin(x)[2:]

           str1 = bin(x).replace('0b','')   #去处0b

2.运用运算符的特性(推荐)

1.使用按位异或运算符,特点:“相同得0,不同得1” , python中的表示是 ^

2.将按位异或过的数字,转换位二进制,并求出‘1’的数量。

return bin(x^y).count('1')

相关文章

网友评论

      本文标题:Leetcode 461. Hamming Distance

      本文链接:https://www.haomeiwen.com/subject/aoryxxtx.html