【发布时间】:2009-05-09 18:54:53
【问题描述】:
如何在不实际转换和计数的情况下以二进制表示形式获得 “1”的数量?
例如
def number_of_ones(n):
# do something
# I want to MAKE this FASTER (computationally less complex).
c = 0
while n:
c += n%2
n /= 2
return c
>>> number_of_ones(5)
2
>>> number_of_ones(4)
1
【问题讨论】:
-
@ChrisW- python 和 c 是两种不同的语言
-
这不是完全重复的。 python 中的按位运算比 c 贵得多。
标签: python algorithm discrete-mathematics