Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to count total set bits in all number from 1 to n.
Given a positive integer n, then we change to its binary representation and count the total number of set bits.
Example
Input : n=3 Output : 4
Algorithm
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.
Example Code
# 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))
Output
Enter the value of n10 Total set bit count is 17
Advertisements