my-cnblogs-huqiang

怎样判断一个数用二进制表示中1的个数

解法?

思路:先将一个数化成二进制表示,在用不同的方法来计算1的个数。

方法1:(简单除暴法)

a=[]
count=0
b=int(input())
while b>=0:
        k=b%2
        b=b//2
        a.append(k)//将数字转换成二进制,再将转换而成的二进制存入a列表中
for i in a:
     if i==1:
        count+=1
print(count)
     

方法2:(使用与运算的计算规律)

a=[]
count=0
n=0 b
=int(input()) while b>=0: k=b%2 b=b//2 a.append(k)将数字转换成二进制,再将转换而成的二进制数存入a列表中(逆序存入的)
c=len(a)
m=c-1
while n<=m:
a[n],a[m]=a[m],a[n]
n+=1
m-=1//将二进制的数按顺序排好
for i in a:
if i&1==1:
count+=1
print(count)

方法3:(若题目给的是二进制数是x,则可以直接用x*(x-1)!=0的次数来表示二进制数中1的个数。x*(x-1)的作用是将二进制的最低位1消除

count=1
while x&(x-1)!=0:
        count+=1
        x-=1

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-08-16
  • 2021-10-19
  • 2022-01-11
猜你喜欢
  • 2022-12-23
  • 2021-11-01
  • 2021-08-09
  • 2021-12-15
  • 2022-02-17
  • 2022-12-23
  • 2022-02-07
相关资源
相似解决方案