Count total set bits in all numbers from range L to R | C ++ program for the above approach ; Function to count set bits in x ; Base Case ; Recursive Call ; Function that returns count of set bits present in all numbers from 1 to N ; Initialize the result ; Return the setbit count ; Driver Code ; Given L and R ; Function Call
#include <bits/stdc++.h> NEW_LINE 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 ; }