Count total set bits in all numbers from range L to R | 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 ; Given L and R ; Function Call
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 ( " " + countSetBits ( L , R ) ) ;