Python 程序用于统计 1 至 n 所有数字中的总置位计数。


给定一个正整数 n,然后将其更改为二进制表示并统计已设置位总数。

示例

Input : n=3
Output : 4

算法

Step 1: Input a positive integer data.
Step 2: then convert it to binary form.
Step 3: initialize the variable s = 0.
Step 4: traverse every element and add.
Step 5: display sum.

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

示例代码

# Python program to count set bits
# in all numbers from 1 to n.
def countbits(n):
   # initialize the counter
   c = 0
   for i in range(1, n + 1):
   c += bitsetcount(i)
   return c
   def bitsetcount(x):
      if (x <= 0):
      return 0
      return (0 if int(x % 2) == 0 else 1) + bitsetcount(int(x / 2))
      # Driver program
      n = int(input("Enter the value of n"))
print("Total set bit count is", countbits(n))

输出

Enter the value of n10
Total set bit count is 17

更新时间:2020 年 6 月 23 日

276 次浏览

开启您职业生涯

完成课程即可获得认证

开始
广告