Count unset bits in a range | Function to get no of set bits in the binary representation of ' n ' ; function to count unset 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 unset bits in the range ' l ' to ' r ' in ' n ' ; Driver program to test above
function countSetBits ( n ) { var count = 0 ; while ( n ) { n &= ( n - 1 ) ; count ++ ; } return count ; } function countUnsetBitsInGivenRange ( n , l , r ) { var num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return ( r - l + 1 ) - countSetBits ( n & num ) ; } var n = 80 ; var l = 1 , r = 4 ; document . write ( countUnsetBitsInGivenRange ( n , l , r ) ) ;