Skip to content

Instantly share code, notes, and snippets.

@stoensin
Last active November 5, 2019 06:50
Show Gist options
  • Select an option

  • Save stoensin/c4ec29a3866890f73bc3859d0f290b89 to your computer and use it in GitHub Desktop.

Select an option

Save stoensin/c4ec29a3866890f73bc3859d0f290b89 to your computer and use it in GitHub Desktop.
n&(n-1)作用:将n的二进制表示中的最低位为1的改为0,先看一个简单的例子: n = 10101(二进制),则(n-1) = 10100 ==》n&(n-1) = 10100 可以看到原本最低位为1的那位变为0。可以发现,当n&n-1的时候,得出来的数将n的最右边一位1消除了,如此重复,有几个一变循环几次,直到n = 0。
class _1bit(object):
def hammingWeight(self, num):
count = 0
while num:
num = num & num-1
count += 1
return count
def count1bits(num)
count=0
while num:
num= num & num-1
count+= 1
return count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment