Count unset bits in a range | Java implementation to count unset bits in the given 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
class GFG { static int countSetBits ( int n ) { int count = 0 ; while ( n > 0 ) { n &= ( n - 1 ) ; count ++ ; } return count ; } static int countUnsetBitsInGivenRange ( int n , int l , int r ) { int num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) ; return ( r - l + 1 ) - countSetBits ( n & num ) ; } public static void main ( String [ ] args ) { int n = 80 ; int l = 1 , r = 4 ; System . out . print ( countUnsetBitsInGivenRange ( n , l , r ) ) ; } }