计算给定整数中 1 的数量 [英] count number of ones in a given integer

查看:39
本文介绍了计算给定整数中 1 的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

假设你得到一个数字20,它是二进制的10100,所以1的个数是2.

解决方案

使用很棒的集合 模块.

<预><代码>>>>从集合导入计数器>>>二进制 = bin(20)[2:]>>>计数器(二进制)计数器({'0':3,'1':2})

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

<预><代码>>>>二进制 = bin(20)[2:]>>>binary.count('1')2

甚至:

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

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

How do you count the number of ones in a given integer's binary representation.

Say you are given a number 20, which is 10100 in binary, so number of ones is 2.

解决方案

Use the awesome collections module.

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

Or you can use the built-in function count():

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

Or even:

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

But that last solution is slower than using count()

这篇关于计算给定整数中 1 的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆