- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

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 −

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))

5

7

- Related Questions & Answers
- Python program to count total set bits in all number from 1 to n.
- C# program to count total set bits in a number
- C# program to count total bits in a number
- Java program to count total bits in a number
- Write a python program to count total bits in a number?
- Count of numbers having only 1 set bit in the range [0, n] in C++
- Python Count set bits in a range?
- Program to count number of stepping numbers of n digits in python
- Program to find higher number with same number of set bits as n in Python?\n
- Python program to count unset bits in a range.
- Count total bits in a number in C++
- Count total number of digits from 1 to N in C++
- Python Program to Count set bits in an integer
- 8085 program to count total even numbers in series of 10 numbers
- 8085 program to count total odd numbers in series of 10 numbers

Advertisements