4

二进制中1的个数(算法10)

 2 years ago
source link: https://allenwind.github.io/blog/2904/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Mr.Feng Blog

NLP、深度学习、机器学习、Python、Go

二进制中1的个数(算法10)

问题:实现一个函数,统计输入数字中一的个数

如果你知道位运算中的一个特点,这道题就简单了。

数字666的二进制形式是1010011010,注意到(666-1)的二进制为1010011000,观察发现,就是666消去了一个数字1。那么666在消去一个数字1后剩下的部分可以通过位运算留下:666&(666-1)。利用这种特性,添加一个计数器,计算每次消去数字和保留剩下部分的次数。该次数就是我们需要的结果。

def number_of_one(n):
counter = 0
while n:
counter += 1
n = (n-1) & n
return counter
import random

def main():
for _ in range(10):
n = random.randint(1, 100)
print(n, bin(n), number_of_one(n), sep='-->')

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK