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 to test above
' NEW_LINE def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while n : NEW_LINE INDENT n &= ( n - 1 ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countUnsetBitsInGivenRange ( n , l , r ) : NEW_LINE INDENT num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT return ( r - l + 1 ) - countSetBits ( n & num ) NEW_LINE DEDENT n = 80 NEW_LINE l = 1 NEW_LINE r = 4 NEW_LINE print ( countUnsetBitsInGivenRange ( n , l , r ) ) NEW_LINE