给定一个正整数n,计算从1到n的所有数字的二进制表示中的设置位总数。
null
例如:
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的所有数字中的总设置位 链接我们可以使用python解决这个问题 地图() 作用方法很简单,
- 编写一个函数,首先使用 bin(num) 函数,并返回其中的设置位计数。
- 将用户定义的函数映射到从1到n的数字列表中,我们将得到每个数字中设置位的单个计数列表。
- 将所有设定位的计数相加。
# 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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END