Count set bits in a range | C ++ implementation to count set bits in the given range ; Function to get no of set bits in the binary representation of ' n ' ; function to count set bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; returns number of set bits in the range ' l ' to ' r ' in ' n ' ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int countSetBits ( int n ) { unsigned int count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } unsigned int countSetBitsInGivenRange ( unsigned int n , unsigned int l , unsigned int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return countSetBits ( n & num ) ; } int main ( ) { unsigned int n = 42 ; unsigned int l = 2 , r = 5 ; cout << countSetBitsInGivenRange ( n , l , r ) ; return 0 ; }