Count set bits in a 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
function countSetBits ( n ) { let count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } function countSetBitsInGivenRange ( n , l , r ) { let num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return countSetBits ( n & num ) ; } let n = 42 ; let l = 2 , r = 5 ; document . write ( countSetBitsInGivenRange ( n , l , r ) ) ;