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 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
function count_numbers ( L , R ) { let ans = 0 ; for ( let n = L ; n <= R ; n ++ ) { let no_of_bits = Math . floor ( Math . log ( n ) + 1 ) ; let no_of_set_bits = bitCount ( n ) ; if ( no_of_bits - no_of_set_bits == 1 ) { ans ++ ; } } return ans ; } function bitCount ( x ) { let setBits = 0 ; while ( x != 0 ) { x = x & ( x - 1 ) ; setBits ++ ; } return setBits ; } let L = 4 , R = 9 ; document . write ( count_numbers ( L , R ) ) ;