Count of numbers having only one unset bit in a range [ L , R ] | 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
function count_numbers ( L , R ) { let ans = 0 ; let LogR = ( Math . log ( R ) + 1 ) ; for ( let zero_bit = 0 ; zero_bit < LogR ; zero_bit ++ ) { let cur = 0 ; for ( let j = 0 ; j < zero_bit ; j ++ ) { cur |= ( 1 << j ) ; } for ( let j = zero_bit + 1 ; j < LogR ; j ++ ) { cur |= ( 1 << j ) ; if ( cur >= L && cur <= R ) { ans ++ ; } } } return ans ; } let L = 4 , R = 9 ; document . write ( count_numbers ( L , R ) ) ;