Count total set bits in all numbers from range L to R
Given two positive integers L and R, the task is to count the total number of set bits in the binary representation of all the numbers from L to R.
Examples:
Input: L = 3, R = 5
Output: 5
Explanation: (3)10 = (11)2, (4)10 = (100)2, (5)10 = (101)2
So, Total set bit in range 3 to 5 is 5
Input: L = 10, R = 15
Output: 17
Method 1 – Naive Approach: The idea is to run a loop from L to R and sum the count of set bits in all numbers from L to R.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int
countSetBitsUtil(unsigned int x)
{
if (x <= 0)
return 0;
return ((x % 2 == 0 ? 0 : 1)
+ countSetBitsUtil(x / 2));
}
unsigned int countSetBits(unsigned int L,
unsigned int R)
{
int bitCount = 0;
for ( int i = L; i <= R; i++) {
bitCount += countSetBitsUtil(i);
}
return bitCount;
}
int main()
{
int L = 3, R = 5;
printf ( "Total set bit count is %d" ,
countSetBits(L, R));
return 0;
}
|
Java
class GFG{
static int countSetBitsUtil( int x)
{
if (x <= 0 )
return 0 ;
return ((x % 2 == 0 ? 0 : 1 ) +
countSetBitsUtil(x / 2 ));
}
static int countSetBits( int L, int R)
{
int bitCount = 0 ;
for ( int i = L; i <= R; i++)
{
bitCount += countSetBitsUtil(i);
}
return bitCount;
}
public static void main(String[] args)
{
int L = 3 , R = 5 ;
System.out.printf( "Total set bit count is %d" ,
countSetBits(L, R));
}
}
|
Python3
def countSetBitsUtil(x):
if (x < 1 ):
return 0 ;
if (x % 2 = = 0 ):
return 0 ;
else :
return 1 + (countSetBitsUtil(x / 2 ));
def countSetBits(L, R):
bitCount = 0 ;
for i in range (L, R + 1 ):
bitCount + = countSetBitsUtil(i);
return bitCount;
if __name__ = = '__main__' :
L = 3 ;
R = 5 ;
print ( "Total set bit count is " ,
countSetBits(L, R));
|
C#
using System;
class GFG{
static int countSetBitsUtil( int x)
{
if (x <= 0)
return 0;
return ((x % 2 == 0 ? 0 : 1) +
countSetBitsUtil(x / 2));
}
static int countSetBits( int L, int R)
{
int bitCount = 0;
for ( int i = L; i <= R; i++)
{
bitCount += countSetBitsUtil(i);
}
return bitCount;
}
public static void Main(String[] args)
{
int L = 3, R = 5;
Console.Write( "Total set bit count is {0}" ,
countSetBits(L, R));
}
}
|
Javascript
<script>
function countSetBitsUtil(x)
{
if (x <= 0)
return 0;
return ((x % 2 == 0 ? 0 : 1)
+ countSetBitsUtil(parseInt(x / 2)));
}
function countSetBits(L, R)
{
var bitCount = 0;
for ( var i = L; i <= R; i++) {
bitCount += countSetBitsUtil(i);
}
return bitCount;
}
var L = 3, R = 5;
document.write( "Total set bit count is " +
countSetBits(L, R));
</script>
|
Output:
Total set bit count is 5
Time Complexity: O(N*Log N)
Auxiliary Space: O(1)
Method 2 – Better Approach: The idea is to observe bits from the rightmost side at distance i then bits get inverted after 2i position in vertical sequence.
Example:
L = 3, R = 5
0 = 0000
1 = 0001
2 = 0010
3 = 0011
4 = 0100
5 = 0101
Observe the right most bit (i = 0) the bits get flipped after (20 = 1)
Observe the 3rd rightmost bit (i = 2) the bits get flipped after (22 = 4).
Therefore, We can count bits in vertical fashion such that at i’th right most position bits will be get flipped after 2i iteration.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int countSetBit( int n)
{
int i = 0;
int ans = 0;
while ((1 << i) <= n) {
bool k = 0;
int change = 1 << i;
for ( int j = 0; j <= n; j++) {
ans += k;
if (change == 1) {
k = !k;
change = 1 << i;
}
else {
change--;
}
}
i++;
}
return ans;
}
int countSetBits( int L, int R)
{
return abs (countSetBit(R)
- countSetBit(L - 1));
}
int main()
{
int L = 3, R = 5;
cout << "Total set bit count is "
<< countSetBits(L, R) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static int countSetBit( int n)
{
int i = 0 ;
int ans = 0 ;
while (( 1 << i) <= n)
{
boolean k = true ;
int change = 1 << i;
for ( int j = 0 ; j <= n; j++)
{
ans += k== true ? 0 : 1 ;
if (change == 1 )
{
k = !k;
change = 1 << i;
}
else
{
change--;
}
}
i++;
}
return ans;
}
static int countSetBits( int L, int R)
{
return Math.abs(countSetBit(R) -
countSetBit(L - 1 ));
}
public static void main(String[] args)
{
int L = 3 , R = 5 ;
System.out.print( "Total set bit count is " +
countSetBits(L, R) + "\n" );
}
}
|
Python3
def countSetBit(n):
i = 0 ;
ans = 0 ;
while (( 1 << i) < = n):
k = True ;
change = 1 << i;
for j in range (n + 1 ):
ans + = 0 if k = = True else 1 ;
if (change = = 1 ):
k = False if k = = True else True ;
change = 1 << i;
else :
change - = 1 ;
i + = 1 ;
return ans;
def countSetBits(L, R):
return abs (countSetBit(R) -
countSetBit(L - 1 ));
if __name__ = = '__main__' :
L = 3 ;
R = 5 ;
print ( "Total set bit count is " ,
countSetBits(L, R));
|
C#
using System;
class GFG{
static int countSetBit( int n)
{
int i = 0;
int ans = 0;
while ((1 << i) <= n)
{
bool k = true ;
int change = 1 << i;
for ( int j = 0; j <= n; j++)
{
ans += k== true ?0:1;
if (change == 1)
{
k = !k;
change = 1 << i;
}
else
{
change--;
}
}
i++;
}
return ans;
}
static int countSetBits( int L, int R)
{
return Math.Abs(countSetBit(R) -
countSetBit(L - 1));
}
public static void Main(String[] args)
{
int L = 3, R = 5;
Console.Write( "Total set bit count is " +
countSetBits(L, R) + "\n" );
}
}
|
Javascript
<script>
function countSetBit(n)
{
var i = 0;
var ans = 0;
while ((1 << i) <= n) {
var k = 0;
var change = 1 << i;
for ( var j = 0; j <= n; j++) {
ans += k;
if (change == 1) {
k = !k;
change = 1 << i;
}
else {
change--;
}
}
i++;
}
return ans;
}
function countSetBits(L, R)
{
return Math.abs(countSetBit(R)
- countSetBit(L - 1));
}
var L = 3, R = 5;
document.write( "Total set bit count is "
+ countSetBits(L, R) );
</script>
|
Output:
Total set bit count is 5
Time Complexity: O((L + R)*K), where K is the number of bits in L and R.
Auxiliary Space: O(1)
Method 3 – Tricky If the input number is of form 2b – 1 e.g., 1, 3, 7, 15, … etc, the number of set bits is b * 2(b-1). This is because for all the numbers 0 to 2b – 1, if you complement and flip the list you end up with the same list (half the bits are set and half bits are unset).
If the number does not have all set bits, then let m is the position of the leftmost set bit. The number of set bits in that position is n – (1 << m) + 1. The remaining set bits are in two parts:
- The bits in the (m – 1) positions down to the point where the leftmost bit becomes 0
- The 2(m – 1) numbers below that point, which is the closed form above.
For Example: N = 6
0|0 0
0|0 1
0|1 0
0|1 1
-|--
1|0 0
1|0 1
1|1 0
From the above we have:
- The leftmost set bit is in position 2 (positions are considered starting from 0).
- If we mask that off what remains is 2 (the “1 0” in the right part of the last row), So the number of bits in the 2nd position (the lower left box) is 3 (that is, 2 + 1).
- The set bits from 0-3 (the upper right box above) is 2*2(2 – 1) = 4.
- The box in the lower right is the remaining bits we haven’t yet counted and is the number of set bits for all the numbers up to 2 (the value of the last entry in the lower right box) which can be figured recursively.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
unsigned int countSetBit(unsigned int n);
unsigned int getLeftmostBit( int n)
{
int m = 0;
while (n > 1) {
n = n >> 1;
m++;
}
return m;
}
unsigned int getNextLeftmostBit( int n, int m)
{
unsigned int temp = 1 << m;
while (n < temp) {
temp = temp >> 1;
m--;
}
return m;
}
unsigned int _countSetBit(unsigned int n,
int m)
{
if (n == 0)
return 0;
m = getNextLeftmostBit(n, m);
if (n == ((unsigned int )1 << (m + 1)) - 1)
return (unsigned int )(m + 1) * (1 << m);
n = n - (1 << m);
return ((n + 1)
+ countSetBit(n)
+ m * (1 << (m - 1)));
}
unsigned int countSetBit(unsigned int n)
{
int m = getLeftmostBit(n);
return _countSetBit(n, m);
}
int countSetBits( int L, int R)
{
return abs (countSetBit(R)
- countSetBit(L - 1));
}
int main()
{
int L = 3, R = 5;
cout << "Total set bit count is "
<< countSetBits(L, R);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int getLeftmostBit( int n)
{
int m = 0 ;
while (n > 1 )
{
n = n >> 1 ;
m++;
}
return m;
}
static int getNextLeftmostBit( int n, int m)
{
int temp = 1 << m;
while (n < temp)
{
temp = temp >> 1 ;
m--;
}
return m;
}
static int countSetBit( int n)
{
int m = getLeftmostBit(n);
return _countSetBit(n, m);
}
static int _countSetBit( int n, int m)
{
if (n == 0 )
return 0 ;
m = getNextLeftmostBit(n, m);
if (n == (( int ) 1 << (m + 1 )) - 1 )
return ( int )(m + 1 ) * ( 1 << m);
n = n - ( 1 << m);
return ((n + 1 ) +
countSetBit(n) +
m * ( 1 << (m - 1 )));
}
static int countSetBits( int L, int R)
{
return Math.abs(countSetBit(R) -
countSetBit(L - 1 ));
}
public static void main(String[] args)
{
int L = 3 , R = 5 ;
System.out.print( "Total set bit count is " +
countSetBits(L, R));
}
}
|
Python3
def getLeftmostBit(n):
m = 0 ;
while (n > 1 ):
n = n >> 1 ;
m + = 1 ;
return m;
def getNextLeftmostBit(n, m):
temp = 1 << m;
while (n < temp):
temp = temp >> 1 ;
m - = 1 ;
return m;
def countSetBit(n):
m = getLeftmostBit(n);
return _countSetBit(n, m);
def _countSetBit(n, m):
if (n = = 0 ):
return 0 ;
m = getNextLeftmostBit(n, m);
if (n = = int ( 1 << (m + 1 )) - 1 ):
return int (m + 1 ) * ( 1 << m);
n = n - ( 1 << m);
return ((n + 1 ) + countSetBit(n) + m * ( 1 << (m - 1 )));
def countSetBits(L, R):
return abs (countSetBit(R) - countSetBit(L - 1 ));
if __name__ = = '__main__' :
L = 3 ;
R = 5 ;
print ( "Total set bit count is " , countSetBits(L, R));
|
C#
using System;
class GFG{
static int getLeftmostBit( int n)
{
int m = 0;
while (n > 1)
{
n = n >> 1;
m++;
}
return m;
}
static int getNextLeftmostBit( int n, int m)
{
int temp = 1 << m;
while (n < temp)
{
temp = temp >> 1;
m--;
}
return m;
}
static int countSetBit( int n)
{
int m = getLeftmostBit(n);
return _countSetBit(n, m);
}
static int _countSetBit( int n, int m)
{
if (n == 0)
return 0;
m = getNextLeftmostBit(n, m);
if (n == (( int )1 << (m + 1)) - 1)
return ( int )(m + 1) * (1 << m);
n = n - (1 << m);
return ((n + 1) +
countSetBit(n) +
m * (1 << (m - 1)));
}
static int countSetBits( int L, int R)
{
return Math.Abs(countSetBit(R) -
countSetBit(L - 1));
}
public static void Main(String[] args)
{
int L = 3, R = 5;
Console.Write( "Total set bit count is " +
countSetBits(L, R));
}
}
|
Javascript
<script>
function getLeftmostBit(n)
{
var m = 0;
while (n > 1)
{
n = n >> 1;
m++;
}
return m;
}
function getNextLeftmostBit(n, m)
{
var temp = 1 << m;
while (n < temp)
{
temp = temp >> 1;
m--;
}
return m;
}
function countSetBit(n)
{
var m = getLeftmostBit(n);
return _countSetBit(n, m);
}
function _countSetBit(n, m)
{
if (n == 0)
return 0;
m = getNextLeftmostBit(n, m);
if (n == (1 << (m + 1)) - 1)
return (m + 1) * (1 << m);
n = n - (1 << m);
return ((n + 1) +
countSetBit(n) +
m * (1 << (m - 1)));
}
function countSetBits(L, R)
{
return Math.abs(countSetBit(R) -
countSetBit(L - 1));
}
var L = 3, R = 5;
document.write( "Total set bit count is " +
countSetBits(L, R));
</script>
|
Output:
Total set bit count is 5
Time Complexity: O(log N)
Auxiliary Space: O(1)
Method 4 – using setbit: In setbit method count one by one set bit of each number in range L to R using last bit, check to last bit and if it is set then increase the count and finally sum up over it.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
int countSetBits( int L, int R)
{
int count = 0;
for ( int i = L; i <= R; i++) {
int n = i;
while (n > 0) {
count += (n & 1);
n = n >> 1;
}
}
return count;
}
int main()
{
int L = 3, R = 5;
cout << "Total set Bit count is "
<< countSetBits(L, R);
return 0;
}
|
Java
class GFG{
static int countSetBits( int L, int R)
{
int count = 0 ;
for ( int i = L; i <= R; i++)
{
int n = i;
while (n > 0 )
{
count += (n & 1 );
n = n >> 1 ;
}
}
return count;
}
public static void main(String[] args)
{
int L = 3 , R = 5 ;
System.out.print( "Total set Bit count is " +
countSetBits(L, R));
}
}
|
Python3
def countSetBits(L, R):
count = 0 ;
for i in range (L, R + 1 ):
n = i;
while (n > 0 ):
count + = (n & 1 );
n = n >> 1 ;
return count;
if __name__ = = '__main__' :
L = 3 ; R = 5 ;
print ( "Total set Bit count is " ,
countSetBits(L, R));
|
C#
using System;
class GFG{
static int countSetBits( int L, int R)
{
int count = 0;
for ( int i = L; i <= R; i++)
{
int n = i;
while (n > 0)
{
count += (n & 1);
n = n >> 1;
}
}
return count;
}
public static void Main(String[] args)
{
int L = 3, R = 5;
Console.Write( "Total set Bit count is " +
countSetBits(L, R));
}
}
|
Javascript
<script>
function countSetBits(L, R)
{
let count = 0;
for (let i = L; i <= R; i++)
{
let n = i;
while (n > 0)
{
count += (n & 1);
n = n >> 1;
}
}
return count;
}
let L = 3, R = 5;
document.write( "Total set Bit count is " +
countSetBits(L, R));
</script>
|
Output:
Total set Bit count is 5
Time Complexity: O(N*logN)
Auxiliary Space: O(1)
Method 5 – Using STL __builtin_popcount() function: STL provides an inbuilt function for counting set a bit in an integer, so here call that function for every number in range L to R and count set bits.
C++
#include <iostream>
using namespace std;
int countSetBits( int L, int R)
{
int count = 0;
for ( int i = L; i <= R; i++) {
count += __builtin_popcount(i);
}
return count;
}
int main()
{
int L = 3, R = 5;
cout << "Total set bit count is "
<< countSetBits(L, R);
return 0;
}
|
Java
class GFG{
static int countSetBits( int L, int R)
{
int count = 0 ;
for ( int i = L; i <= R; i++)
{
count += Integer.bitCount(i);
}
return count;
}
public static void main(String[] args)
{
int L = 3 , R = 5 ;
System.out.print( "Total set bit count is " +
countSetBits(L, R));
}
}
|
Python3
def countSetBits(L, R):
count = 0 ;
for i in range (L, R + 1 ):
count + = countSetBit(i);
return count;
def countSetBit(n):
count = 0
while (n):
count + = n & 1
n >> = 1
return count
if __name__ = = '__main__' :
L = 3 ;
R = 5 ;
print ( "Total set bit count is " ,
countSetBits(L, R));
|
C#
using System;
class GFG{
static int countSetBits( int L, int R)
{
int count = 0;
for ( int i = L; i <= R; i++)
{
count += countSetBits(i);
}
return count;
}
static int countSetBits( long x)
{
int setBits = 0;
while (x != 0)
{
x = x & (x - 1);
setBits++;
}
return setBits;
}
public static void Main(String[] args)
{
int L = 3, R = 5;
Console.Write( "Total set bit count is " +
countSetBits(L, R));
}
}
|
Javascript
<script>
function countSetBits(L, R)
{
let count = 0;
for (let i = L; i <= R; i++)
{
count = Number(i.toString().split( "" ).sort());
}
return count;
}
let L = 3, R = 5;
document.write( "Total set bit count is " +
countSetBits(L, R));
</script>
|
Output:
Total set bit count is 5
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
11 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...