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 code
< ? php function countSetBits ( $ n ) { $ count = 0 ; while ( $ n ) { $ n &= ( $ n - 1 ) ; $ count ++ ; } return $ count ; } function countUnsetBitsInGivenRange ( $ n , $ l , $ r ) { $ num = ( ( 1 << $ r ) - 1 ) ^ ( ( 1 << ( $ l - 1 ) ) - 1 ) ; return ( $ r - $ l + 1 ) - countSetBits ( $ n & $ num ) ; } $ n = 80 ; $ l = 1 ; $ r = 4 ; echo countUnsetBitsInGivenRange ( $ n , $ l , $ r ) ; ? >