Count total set bits in all numbers from range L to R | C ++ program for the above approach ; Function to count set bit in range ; Count variable ; Find the set bit in Nth number ; If last bit is set ; Left sift by one bit ; Return count ; Driver Code ; Given Range L and R ; Function Call
#include <iostream> NEW_LINE 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 ; }