text: Count numbers up to N whose rightmost set bit is K | C ++ 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: #include <bits/stdc++.h> NEW_LINE using namespace std ; int countNumberHavingKthBitSet ( int N , int K ) { int numbers_rightmost_setbit_K ; 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 ; } } cout << numbers_rightmost_setbit_K ; } int main ( ) { int N = 15 ; int K = 2 ; countNumberHavingKthBitSet ( N , K ) ; return 0 ; }