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.
范例程式码
# 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
热门推荐
10 送情侣生日祝福语简短
11 六一互换礼物祝福语简短
12 包红包祝福语简短朋友
13 生日祝福语贺卡文字简短
14 生日祝福语大全简短霸气
15 结婚转账祝福语高级简短
16 小派妈妈生日祝福语简短
17 周年庆典祝福语致辞简短
18 新人给朋友祝福语简短