text: Count numbers up to N whose rightmost set bit is K | Java program for the above approach ; Function to count the numbers in the range [ 1 , N ] whose rightmost set bit is K ; Stores the number whose rightmost set bit is K ; Numbers whose rightmost set bit is i ; Subtracting the number whose rightmost set bit is i , from N ; Since i = k , then the number whose rightmost set bit is K is stored ; Driver Code
code: import java . util . Arrays ; class GFG { static void countNumberHavingKthBitSet ( int N , int K ) { int numbers_rightmost_setbit_K = 0 ; for ( int i = 1 ; i <= K ; i ++ ) { int numbers_rightmost_bit_i = ( N + 1 ) / 2 ; N -= numbers_rightmost_bit_i ; if ( i == K ) { numbers_rightmost_setbit_K = numbers_rightmost_bit_i ; } } System . out . println ( numbers_rightmost_setbit_K ) ; } static public void main ( String args [ ] ) { int N = 15 ; int K = 2 ; countNumberHavingKthBitSet ( N , K ) ; } }