양의 정수 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