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 = 4
Input: 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++
#include <bits/stdc++.h>
using namespace std;
int countSetBits( int n)
{
int cnt = 0;
vector< int > setBits(n + 1);
setBits[0] = 0;
for ( int i = 1; i <= n; i++) {
setBits[i] = setBits[i >> 1] + (i & 1);
}
for ( int i = 0; i <= n; i++) {
cnt = cnt + setBits[i];
}
return cnt;
}
int main()
{
int n = 6;
cout << countSetBits(n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int countSetBits( int n)
{
int cnt = 0 ;
int [] setBits = new int [n + 1 ];
setBits[ 0 ] = 0 ;
for ( int i = 1 ; i <= n; i++) {
setBits[i] = setBits[i >> 1 ] + (i & 1 );
}
for ( int i = 0 ; i <= n; i++) {
cnt = cnt + setBits[i];
}
return cnt;
}
public static void main(String[] args)
{
int n = 6 ;
System.out.println(countSetBits(n));
}
}
|
Python3
def countSetBits(n):
cnt = 0
setBits = [ 0 for x in range (n + 1 )]
setBits[ 0 ] = 0
for i in range ( 1 , n + 1 ):
setBits[i] = setBits[i / / 2 ] + (i & 1 )
for i in range ( 0 , n + 1 ):
cnt = cnt + setBits[i]
return cnt
n = 6
print (countSetBits(n))
|
C#
using System;
class GFG {
static int countSetBits( int n)
{
int cnt = 0;
int [] setBits = new int [n + 1];
setBits[0] = 0;
setBits[1] = 1;
for ( int i = 2; i <= n; i++) {
if (i % 2 == 0) {
setBits[i] = setBits[i / 2];
}
else {
setBits[i] = setBits[i - 1] + 1;
}
}
for ( int i = 0; i <= n; i++) {
cnt = cnt + setBits[i];
}
return cnt;
}
static public void Main()
{
int n = 6;
Console.WriteLine(countSetBits(n));
}
}
|
Javascript
<script>
function countSetBits(n)
{
var cnt = 0;
var setBits = Array.from(
{length: n + 1}, (_, i) => 0);
setBits[0] = 0;
setBits[1] = 1;
for (i = 2; i <= n; i++)
{
if (i % 2 == 0)
{
setBits[i] = setBits[i / 2];
}
else
{
setBits[i] = setBits[i - 1] + 1;
}
}
for (i = 0; i <= n; i++)
{
cnt = cnt + setBits[i];
}
return cnt;
}
var n = 6;
document.write(countSetBits(n));
</script>
|
Time Complexity: O(N), where N is the given number.
Auxiliary Space: O(N), for creating an additional array of size N + 1.
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++
#include <bits/stdc++.h>
using namespace std;
int countSetBits( int n)
{
int cnt = 0;
for ( int i = 1; i <= n; i++) {
cnt = cnt + __builtin_popcount(i);
}
return cnt;
}
int main()
{
int n = 6;
cout << countSetBits(n);
return 0;
}
|
Java
import java.util.*;
class GFG {
static int countSetBits( int n)
{
int cnt = 0 ;
for ( int i = 1 ; i <= n; i++) {
cnt = cnt + Integer.bitCount(i);
}
return cnt;
}
public static void main(String[] args)
{
int n = 6 ;
System.out.print(countSetBits(n));
}
}
|
Python3
def countSetBits(n):
cnt = 0
for i in range ( 1 , n + 1 ):
cnt = cnt + ( bin (i)[ 2 :]).count( '1' )
return cnt
if __name__ = = '__main__' :
n = 6
print (countSetBits(n))
|
Javascript
<script>
function bitCount (n) {
n = n - ((n >> 1) & 0x55555555)
n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}
function countSetBits(n) {
var cnt = 0;
for (i = 1; i <= n; i++) {
cnt = cnt + bitCount(i);
}
return cnt;
}
var n = 6;
document.write(countSetBits(n));
</script>
|
C#
using System;
using System.Linq;
public class GFG {
static int countSetBits( int n)
{
int cnt = 0;
for ( int i = 1; i <= n; i++) {
cnt = cnt
+ (Convert.ToString(i, 2).Count(
c = > c == '1' ));
}
return cnt;
}
public static void Main(String[] args)
{
int n = 6;
Console.Write(countSetBits(n));
}
}
|
Time Complexity: O(NlogN), where N is the given number.
Auxiliary Space: O(1)
Another approach : Space optimized without use of built-in function
To optimize the space of the previous approach we can avoid using a vector to store the set bits count for every integer in the range [1, n]. Instead, we can use a single variable to store the total count of set bits.
Implementation Steps:
- Initialize a variable ‘cnt’ to 0.
- Iterate from 1 to n.
- For each i, create a variable ‘x’ and set it to i.
- While x is greater than 0, do the following:
- a. If the least significant bit of x is 1, increment ‘cnt’.
- b. Right shift x by 1 bit.
- Return cnt as the count of set bits in integers from 1 to n.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int countSetBits( int n)
{
int cnt = 0;
for ( int i = 1; i <= n; i++) {
int x = i;
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
int main()
{
int n = 6;
cout << countSetBits(n);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int countSetBits( int n)
{
int cnt = 0 ;
for ( int i = 1 ; i <= n; i++) {
int x = i;
while (x > 0 ) {
cnt += (x & 1 );
x >>= 1 ;
}
}
return cnt;
}
public static void main(String[] args) {
int n = 6 ;
System.out.println(countSetBits(n));
}
}
|
Python
def countSetBits(n):
cnt = 0
for i in range ( 1 , n + 1 ):
x = i
while x > 0 :
cnt + = (x & 1 )
x >> = 1
return cnt
n = 6
print (countSetBits(n))
|
Javascript
function countSetBits(n) {
let cnt = 0;
for (let i = 1; i <= n; i++) {
let x = i;
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
let n = 6;
console.log(countSetBits(n));
|
C#
using System;
class GFG {
public static int CountSetBits( int n)
{
int cnt = 0;
for ( int i = 1; i <= n; i++) {
int x = i;
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
public static void Main( string [] args)
{
int n = 6;
Console.WriteLine(CountSetBits(n));
}
}
|
Output
9
Time Complexity: O(NlogN), where N is the given number.
Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
26 Apr, 2023
Like Article
Save Article