Given a positive integer N, the task is to count the total number of set bits in binary representation of all the numbers from 1 to N.
Examples:
Input: N = 3
Output: 4
setBits(1) + setBits(2) + setBits(3) = 1 + 1 + 2 = 4Input: N = 6
Output: 9
Approach: Solution to this problem has been published in the Set 1 and the Set 2 of this article. Here, a dynamic programming based approach is discussed.
- Base case: Number of set bits in 0 is 0.
- For any number n: n and n>>1 has same no of set bits except for the rightmost bit.
Example: n = 11 (1011), n >> 1 = 5 (101)… same bits in 11 and 5 are marked bold. So assuming we already know set bit count of 5, we only need to take care for the rightmost bit of 11 which is 1. setBit(11) = setBit(5) + 1 = 2 + 1 = 3
Rightmost bit is 1 for odd and 0 for even number.
Recurrence Relation: setBit(n) = setBit(n>>1) + (n & 1) and setBit(0) = 0
We can use bottom-up dynamic programming approach to solve this.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;// Function to return the count of// set bits in all the integers// from the range [1, n]int countSetBits(int n){ // To store the required count // of the set bits int cnt = 0; // To store the count of set // bits in every integer vector<int> setBits(n + 1); // 0 has no set bit setBits[0] = 0; for (int i = 1; i <= n; i++) { setBits[i] = setBits[i >> 1] + (i & 1); } // Sum all the set bits for (int i = 0; i <= n; i++) { cnt = cnt + setBits[i]; } return cnt;}// Driver codeint main(){ int n = 6; cout << countSetBits(n); return 0;} |
Java
// Java implementation of the approachimport java.util.*;class GFG{// Function to return the count of// set bits in all the integers// from the range [1, n]static int countSetBits(int n){ // To store the required count // of the set bits int cnt = 0; // To store the count of set // bits in every integer int []setBits = new int[n + 1]; // 0 has no set bit setBits[0] = 0; // For the rest of the elements for (int i = 1; i <= n; i++) { setBits[i] = setBits[i >> 1] + (i & 1); } // Sum all the set bits for (int i = 0; i <= n; i++) { cnt = cnt + setBits[i]; } return cnt;}// Driver codepublic static void main(String[] args){ int n = 6; System.out.println(countSetBits(n));}}// This code is contributed by Princi Singh |
Python3
# Python3 implementation of the approach# Function to return the count of# set bits in all the integers# from the range [1, n]def countSetBits(n): # To store the required count # of the set bits cnt = 0 # To store the count of set # bits in every integer setBits = [0 for x in range(n + 1)] # 0 has no set bit setBits[0] = 0 # For the rest of the elements for i in range(1, n + 1): setBits[i] = setBits[i // 2] + (i & 1) # Sum all the set bits for i in range(0, n + 1): cnt = cnt + setBits[i] return cnt# Driver coden = 6print(countSetBits(n))# This code is contributed by Sanjit Prasad |
C#
// C# implementation of the approachusing System;class GFG{ // Function to return the count of // set bits in all the integers // from the range [1, n] static int countSetBits(int n) { // To store the required count // of the set bits int cnt = 0; // To store the count of set // bits in every integer int []setBits = new int[n + 1]; // 0 has no set bit setBits[0] = 0; // 1 has a single set bit setBits[1] = 1; // For the rest of the elements for (int i = 2; i <= n; i++) { // If current element i is even then // it has set bits equal to the count // of the set bits in i / 2 if (i % 2 == 0) { setBits[i] = setBits[i / 2]; } // Else it has set bits equal to one // more than the previous element else { setBits[i] = setBits[i - 1] + 1; } } // Sum all the set bits for (int i = 0; i <= n; i++) { cnt = cnt + setBits[i]; } return cnt; } // Driver code static public void Main () { int n = 6; Console.WriteLine(countSetBits(n)); }}// This code is contributed by AnkitRai01 |
Javascript
<script>// Javascript implementation of the approach// Function to return the count of// set bits in all the integers// from the range [1, n]function countSetBits(n){ // To store the required count // of the set bits var cnt = 0; // To store the count of set // bits in every integer var setBits = Array.from( {length: n + 1}, (_, i) => 0); // 0 has no set bit setBits[0] = 0; // 1 has a single set bit setBits[1] = 1; // For the rest of the elements for(i = 2; i <= n; i++) { // If current element i is even then // it has set bits equal to the count // of the set bits in i / 2 if (i % 2 == 0) { setBits[i] = setBits[i / 2]; } // Else it has set bits equal to one // more than the previous element else { setBits[i] = setBits[i - 1] + 1; } } // Sum all the set bits for(i = 0; i <= n; i++) { cnt = cnt + setBits[i]; } return cnt;}// Driver codevar n = 6;document.write(countSetBits(n));// This code is contributed by 29AjayKumar</script> |
9
Another simple and easy to understand solution:
A simple easy to implement and understand solution would be not using bits operations. The solution is to directly count set bits using __builtin_popcount() .The solution is explained in code using comments.
C++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;// Function to return the count of// set bits in all the integers// from the range [1, n]int countSetBits(int n){ // To store the required count // of the set bits int cnt = 0; // Calculate set bits in each number using // __builtin_popcount() and Sum all the set bits for (int i = 1; i <= n; i++) { cnt = cnt + __builtin_popcount(i); } return cnt;}// Driver codeint main(){ int n = 6; cout << countSetBits(n); return 0;}// This article is contributed by Abhishek |
9
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer DSA Live Classes


