The Hamming Distance [位运算]

前面:

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

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"


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值