Count of numbers having only one unset bit in a range [ L , R ] | Python3 program for the above approach ; Function to count numbers in the range [ l , r ] having exactly one unset bit ; Stores the required count ; Iterate over the range ; Calculate number of bits ; Calculate number of set bits ; If count of unset bits is 1 ; Increment answer ; Return the answer ; Driver Code ; Function call
from math import log2 NEW_LINE def count_numbers ( L , R ) : NEW_LINE INDENT ans = 0 NEW_LINE for n in range ( L , R + 1 ) : NEW_LINE INDENT no_of_bits = int ( log2 ( n ) + 1 ) NEW_LINE no_of_set_bits = bin ( n ) . count ( '1' ) NEW_LINE if ( no_of_bits - no_of_set_bits == 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 4 NEW_LINE R = 9 NEW_LINE print ( count_numbers ( L , R ) ) NEW_LINE DEDENT