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 count elements having one zero in binary ; Stores the maximum number of bits needed to represent number ; Loop over for zero bit position ; Number having zero_bit as unset and remaining bits set ; Sets all bits before zero_bit ; Set the bit at position j ; Set the bit position at j ; If cur is in the range [ L , R ] , then increment ans ; Return ans ; Driver Code ; Function Call
import math NEW_LINE def count_numbers ( L , R ) : NEW_LINE INDENT ans = 0 ; NEW_LINE LogR = ( int ) ( math . log ( R ) + 1 ) ; NEW_LINE for zero_bit in range ( LogR ) : NEW_LINE INDENT cur = 0 ; NEW_LINE for j in range ( zero_bit ) : NEW_LINE INDENT cur |= ( 1 << j ) ; NEW_LINE DEDENT for j in range ( zero_bit + 1 , LogR ) : NEW_LINE INDENT cur |= ( 1 << j ) ; NEW_LINE if ( cur >= L and cur <= R ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT 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