Count total set bits in all numbers from 1 to N | Set 3
Last Updated :
26 Apr, 2023
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++
// 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 code
int main()
{
int n = 6;
cout << countSetBits(n);
return 0;
}
Java
// Java implementation of the approach
import 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 code
public 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 code
n = 6
print(countSetBits(n))
# This code is contributed by Sanjit Prasad
C#
// C# implementation of the approach
using 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 code
var n = 6;
document.write(countSetBits(n));
// This code is contributed by 29AjayKumar
</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++
// 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 code
int main()
{
int n = 6;
cout << countSetBits(n);
return 0;
}
// This article is contributed by Abhishek
Java
// Java implementation of the approach
import 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;
// Calculate set bits in each number using
// Integer.bitCount() and Sum all the set bits
for (int i = 1; i <= n; i++) {
cnt = cnt + Integer.bitCount(i);
}
return cnt;
}
// Driver code
public static void main(String[] args)
{
int n = 6;
System.out.print(countSetBits(n));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python 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
# Calculate set bits in each number using
# Integer.bitCount() and Sum all the set bits
for i in range(1, n+1):
cnt = cnt + (bin(i)[2:]).count('1')
return cnt
# Driver code
if __name__ == '__main__':
n = 6
print(countSetBits(n))
# This code is contributed by Rajput-Ji
JavaScript
<script>
// javascript implementation of the approach
function bitCount (n) {
n = n - ((n >> 1) & 0x55555555)
n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
return ((n + (n >> 4) & 0xF0F0F0F) * 0x1010101) >> 24
}
// 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;
// Calculate set bits in each number using
// Integer.bitCount() and Sum all the set bits
for (i = 1; i <= n; i++) {
cnt = cnt + bitCount(i);
}
return cnt;
}
// Driver code
var n = 6;
document.write(countSetBits(n));
// This code is contributed by Rajput-Ji
</script>
C#
// C# implementation of the approach
using System;
using System.Linq;
public 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;
// Calculate set bits in each number using
// int.bitCount() and Sum all the set bits
for (int i = 1; i <= n; i++) {
cnt = cnt
+ (Convert.ToString(i, 2).Count(
c = > c == '1'));
}
return cnt;
}
// Driver code
public static void Main(String[] args)
{
int n = 6;
Console.Write(countSetBits(n));
}
}
// This code is contributed by Rajput-Ji
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++
// 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;
for (int i = 1; i <= n; i++) {
int x = i;
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
// Driver code
int main()
{
int n = 6;
cout << countSetBits(n);
return 0;
}
Java
// Java code addition
import java.util.*;
public class Main {
// Function to return the count of
// set bits in all the integers
// from the range [1, n]
public static int countSetBits(int n)
{
// To store the required count
// of the set bits
int cnt = 0;
for (int i = 1; i <= n; i++) {
int x = i;
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
// Driver code
public static void main(String[] args) {
int n = 6;
System.out.println(countSetBits(n));
}
}
// The code is contributed by Nidhi goel.
Python
# 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
for i in range(1, n+1):
x = i
while x > 0:
cnt += (x & 1)
x >>= 1
return cnt
# Driver code
n = 6
print(countSetBits(n))
JavaScript
// JavaScript code 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
let cnt = 0;
for (let i = 1; i <= n; i++) {
let x = i;
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
// Driver code
let n = 6;
console.log(countSetBits(n));
C#
using System;
class GFG {
// Function to return the count of
// set bits in all the integers
// from the range [1, n]
public static int CountSetBits(int n)
{
// To store the required count
// of the set bits
int cnt = 0;
for (int i = 1; i <= n; i++) {
int x = i;
while (x > 0) {
cnt += (x & 1);
x >>= 1;
}
}
return cnt;
}
// Driver code
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)
Similar Reads
Count total set bits in all numbers from 1 to n | Set 2
Given a positive integer N, the task is to count the sum of the number of set bits in the binary representation of all the numbers from 1 to N.Examples: Input: N = 3 Output: 4 DecimalBinarySet Bit Count101121013112 1 + 1 + 2 = 4Input: N = 16 Output: 33 Recommended PracticeCount total set bitsTry It!
11 min read
How to Count Set Bits in an Integer in C++?
In binary representation of a number, a set bit is defined as the binary digit (bit) that is set to 1. In this article, we will learn how to count the set bits in a given integer in C++.ExampleInput: 13Output:The number of set bits in 13 (1101) is: 3Counting Set Bits in an IntegerTo count the set bi
2 min read
Count of total bits toggled/flipped in binary representation of 0 to N
Given an integer N, the task is to find the total number of bits toggled to obtain all numbers from 0 to N sequentially. Examples: Input: N = 5 Output: 8 Explanation: Let's represent numbers from 0 to 5 in binary: 000 -> 001 : 1 bit toggled 001 -> 010 : 2 bits toggled 010 -> 011 : 1 bit tog
4 min read
How to Set, Clear, and Toggle a Single Bit in C++?
In bit manipulation, setting a bit, clearing a bit, and toggling a single bit are basic operations. We can easily carry out these operations using the bitwise operators in C++. In this article, we will see how to set, clear, and toggle operations on the Kth bit. Example Input: N = 15, K = 0Output: S
3 min read
Find the number of binary strings of length N with at least 3 consecutive 1s
Given an integer N. The task is to find the number of all possible distinct binary strings of length N which have at least 3 consecutive 1s.Examples: Input: N = 3 Output: 1 The only string of length 3 possible is "111".Input: N = 4 Output: 3 The 3 strings are "1110", "0111" and "1111". Naive approac
9 min read
Count integers in an Array which are multiples their bits counts
Given an array arr[] of N elements, the task is to count all the elements which are a multiple of their set bits count.Examples: Input : arr[] = { 1, 2, 3, 4, 5, 6 } Output : 4 Explanation : There numbers which are multiple of their setbits count are { 1, 2, 4, 6 }. Input : arr[] = {10, 20, 30, 40}
9 min read
Absolute difference between set and unset bit count in N
Prerequisite: Bitset function in STL library Given a number N, the task is to find the absolute difference of the number of set and unset bits of this given number. Examples: Input: N = 14 Output: 2 Explanation: Binary representation of 14 is "1110". Here the number of set bits is 3 and the number o
5 min read
Count of even set bits between XOR of two arrays
Given two arrays A[] and B[] having N and M positive elements respectively. The task is to count the number of elements in array A with even number of set bits in XOR for every element of array B. Examples: Input: A[] = { 4, 2, 15, 9, 8, 8 }, B[] = { 3, 4, 22 } Output: 2 4 4 Explanation: Binary repr
11 min read
Minimum bit flips such that every K consecutive bits contain at least one set bit
Given a binary string S, and an integer K, the task is to find the minimum number of flips required such that every substring of length K contains at least one '1'.Examples: Input: S = "10000001" K = 2 Output: 3 Explanation: We need only 3 changes in string S ( at position 2, 4 and 6 ) so that the s
8 min read
bitset count() in C++ STL
bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. Syntax: int count() Parameter: The function accepts no parameter. Return Value: The function returns the number of set bits. It returns the total number of ones or the number of se
2 min read