1.什么是汉明距离?
两个整数对应二进制位不同位置的数目。例如0001与1010之间对应二进制位不同位置数目是3;0001与0101之间对应二进制位不同位置数目是1.
def hammingDistance(self, x: int, y: int) -> int:
bx = bin(x).replace("0b", "")
by = bin(y).replace("0b", "")
lx = len(bx)
ly = len(by)
lenth = 0
ix, iy = 0, 0
i, j, n = 0, 0, 0
if lx < ly:
lenth = ly
while ix < (ly-lx):
bx = "0" + bx
ix += 1
else:
lenth = lx
while iy < (lx-ly):
by = "0" + by
iy += 1
while i<lenth and j<lenth:
if bx[i] == by[j]:
i+=1
j+=1
else:
n = n+1
i += 1
j += 1
return n
Scala实现汉明距离(主要考察逻辑运算)
object Solution {
def hammingDistance(x: Int, y: Int): Int = {
var v:Int = x^y
var n = 0
while(v != 0){
v = v & (v-1)
n = n+1
}
return n
}
}
来源:CSDN
作者:keepStrive
链接:https://blog.csdn.net/qq_41092109/article/details/103844127