【发布时间】:2019-10-23 08:46:46
【问题描述】:
我想找到一种更好的方法来实现以下目标:
n = 6
k = 1
Flip the 1st significant bit in 6
Variable Binary representation Decimal Representation
n 110 6
m(result) 010 2
我想实现与this wiki 文章中相同的目标
这是我做的,但我觉得有点矫枉过正,效率低下:
def toggleKthSignificantBit(self, n, k):
tmp = list(bin(n)[2:].zfill(3))
tmp[k-1] = str(int(tmp[k-1]) ^ 1)
tmp2 = ''.join(tmp)
print(tmp2)
return int(tmp2, 2)
【问题讨论】:
标签: python bit-manipulation bitwise-operators bit-shift