The Hamming Distance [位运算]

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/welcom_/article/details/83722612

前面:

>>  #右移
<<  #左移
|   #位或 
&   #位与
^   #位异或
~   #非

0b11 << 2   #输出为12, 即0b1100

0b11 >> 1   #输出为1, 即0b1
-8 >> 3     #输出为-1   
'''在Python中如果符号位为0,则右移后高位补0,如果符号位为1,则高位补1;
同样需要先转化为补码再进行计算,以-8 >> 3为例,-8的原码为10...01000,相应的补码为11...11000,右移后变为1...1,相应的原码为10...01,即-1。
右移操作相当于除以2**n,8 >> 3相当于8/(2**3)=1'''
 

思路 : 异或
代码如下:

# The Hamming Distance
# 
def checkio(n, m):
    return str(bin(m^n)).count('1')

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio(117, 17) == 3, "First example"
    assert checkio(1, 2) == 2, "Second example"
    assert checkio(16, 15) == 5, "Third example"


猜你喜欢

转载自blog.csdn.net/welcom_/article/details/83722612