计算给定整数中的1的数量

时间:2013-03-21 06:24:05

标签: python python-2.7

如何计算给定整数二进制表示中的1的数量。

假设您有一个数字20,二进制为10100,因此数字为2。

9 个答案:

答案 0 :(得分:10)

您正在寻找的内容称为Hamming weight,并且有很多算法可以执行此操作。这是另一个直截了当的人:

def ones(n):
    w = 0
    while (n):
        w += 1
        n &= n - 1
    return w

答案 1 :(得分:5)

>>> num = 20
>>> bin(num)[2:].count('1')
2

答案 2 :(得分:3)

使用真棒collections模块。

>>> from collections import Counter
>>> binary = bin(20)[2:]
>>> Counter(binary)
Counter({'0': 3, '1': 2})

或者您可以使用内置函数count()

>>> binary = bin(20)[2:]
>>> binary.count('1')
2

甚至:

>>> sum(1 for i in bin(20)[2:] if i == '1')
2

但最后一个解决方案比使用count()

答案 3 :(得分:3)

快速实现这种炫目的常用方法是使用查找表:

table = [bin(i)[2:].count('1') for i in range(256)]

def pop_count(n):
   cnt = 0
   while n > 0:
     cnt += table[n & 256]
     n >>= 8
   return cnt

在Python中,使用binlist.count的任何解决方案都会更快,但如果你想用汇编程序编写它,这很好。

答案 4 :(得分:1)

str.count方法和bin函数简化了这个小挑战:

>>> def ones(x):
        "Count the number of ones in an integer's binary representation"
        return bin(x).count('1')

>>> ones(20)
2

答案 5 :(得分:1)

int类型自python 3.10a起具有新的方法int.bit_count(),返回给定整数的二进制扩展数(即也称为填充计数),其个数如下:

n = 20
bin(n)
'0b10100'

n.bit_count()返回2,因为它的二进制表示形式中有2个。

答案 6 :(得分:0)

如果输入的号码是'号码'

number =20
len(bin(number)[2:].replace('0',''))

另一种解决方案是

from collections import Counter

Counter(list(bin(number))[2:])['1']

答案 7 :(得分:0)

我是一名新编码员,我发现这个逻辑很简单。新手可能更容易理解。

 "devDependencies": {
  "babel-core": "^6.25.0",
  "babel-loader": "^7.1.0",
  "babel-preset-es2015": "^6.24.1",
  "babel-preset-react": "^6.24.1",
  "css-loader": "^0.28.4",
  "react-hot-loader": "^1.3.1",
  "react-scripts": "1.0.7",
  "serve": "^5.2.4",
  "style-loader": "^0.18.2",
  "webpack": "^3.0.0",
  "webpack-dev-server": "^2.5.0"
},

答案 8 :(得分:0)

您可以使用移>>,按位和&来执行此操作,以检查最低有效位,如下所示:

def count_ones(x):
    result = 0
    while x > 0:
        result += x & 1
        x = x >> 1
    return result

这可以通过向右移位位直到该值变为零,并计算沿途最低有效位为1的次数来实现。

相关问题