Count of numbers having only one unset bit in a range [ L , R ] | Java 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
import java . util . * ; class GFG { static int count_numbers ( int L , int R ) { int ans = 0 ; for ( int n = L ; n <= R ; n ++ ) { int no_of_bits = ( int ) ( Math . log ( n ) + 1 ) ; int no_of_set_bits = Integer . bitCount ( n ) ; if ( no_of_bits - no_of_set_bits == 1 ) { ans ++ ; } } return ans ; } public static void main ( String [ ] args ) { int L = 4 , R = 9 ; System . out . print ( count_numbers ( L , R ) ) ; } }