- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to count total number of set bits of all numbers in range 0 to n in Python

Suppose we have a number num. For each numbers i in the range 0 ≤ i ≤ num we have to calculate the number of 1's in their binary counterpart and return them as a list. So if the number is 5, then the numbers are [0, 1, 2, 3, 4, 5], and number of 1s in these numbers are [0, 1, 1, 2, 1, 2], so it will return 7.

To solve this, we will follow these steps −

res := an array which holds num + 1 number of 0s

offset := 0

for i in range 1 to num + 1

if i and i − 1 = 0, then res[i] := 1 and offset := 0

else increase offset by 1 and res[i] := 1 + res[offset]

return sum of the elements of res

Let us see the following implementation to get better understanding −

## Example

class Solution: def countBits(self, num): result = [0] * (num+1) offset = 0 for i in range(1,num+1): if i & i-1 == 0: result[i] = 1 offset = 0 else: offset+=1 result[i] = 1 + result[offset] return sum(result) ob1 = Solution() print(ob1.countBits(5))

## Input

5

## Output

7

- Related Articles
- Python program to count total set bits in all number from 1 to n.
- C# program to count total set bits in a number
- Write a python program to count total bits in a number?
- Python Count set bits in a range?
- C# program to count total bits in a number
- Java program to count total bits in a number
- Python program to count unset bits in a range.
- Count of numbers having only 1 set bit in the range [0, n] in C++
- Program to find higher number with same number of set bits as n in Python?
- Program to count number of stepping numbers of n digits in python
- Python Program to Count set bits in an integer
- C++ Program to count ordinary numbers in range 1 to n
- Count set bits in a range in C++
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Count total bits in a number in C++

Advertisements