Count total set bits in all numbers from range L to R | Returns position of leftmost set bit The rightmost position is taken as 0 ; Function that gives the position of previous leftmost set bit in n ; Function that returns count of set bits present in all numbers from 1 to n ; Get the position of leftmost set bit in n ; Use the position ; Function to count the set bits between the two numbers N and M ; Base Case ; Get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 ; Update n for next recursive call ; Function that counts the set bits between L and R ; Driver Code Given L and R ; Function call
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 ( " " + countSetBits ( L , R ) ) ;