📌  相关文章
📜  Python map函数|计算从1到n的所有数字中的总置位位数

📅  最后修改于: 2021-05-04 16:39:11             🧑  作者: Mango

给定一个正整数n,计算从1到n的所有数字的二进制表示形式的置位总数。

例子:

Input: n = 3
Output:  4
Binary representations are 1, 2 and 3
1, 10 and 11 respectively. Total set
bits are 1 + 1 + 2 = 4.

Input: n = 6
Output: 9

Input: n = 7
Output: 12

Input: n = 8
Output: 13

我们已有解决此问题的解决方案,请参阅对从1到n的所有数字中的总置位计数。我们可以使用map()函数在Python解决此问题。办法很简单,

  1. 编写一个函数,该函数首先使用bin(num)函数将数字转换为二进制,然后返回其中的设置位数。
  2. 将用户定义的函数映射到从1到n的数字列表中,我们将获得每个数字中设置位的单独计数列表。
  3. 所有设置位的总和。
# Function to Count total set bits in all numbers
# from 1 to n
  
# user defined function
def countSetBit(num):
  
     # convert decimal value into binary and
     # count all 1's in it
     binary = bin(num)
  
     return len([ch for ch in binary if ch=='1'])
  
# function which count set bits in each number
def countSetBitAll(input):
      
    # map count function on each number
    print (sum(map(countSetBit,input)))
  
# Driver program
if __name__ == "__main__":
    n = 8
    input=[]
    for i in range(1,n+1):
         input.append(i)
    countSetBitAll(input)

输出:

13