Count numbers up to N having Kth bit set | Java program for above approach ; Function to return the count of number of 1 's at ith bit  in a range [1, n - 1] ; Store count till nearest power of 2 less than N ; If K - th bit is set in N ; Add to result the nearest power of 2 less than N ; Return result ; Driver code ; Function Call
class GFG { static long getcount ( long n , int k ) { long res = ( n >> ( k + 1 ) ) << k ; if ( ( ( n >> k ) & 1 ) != 0 ) res += n & ( ( 1 << k ) - 1 ) ; return res ; } public static void main ( String [ ] args ) { long N = 14 ; int K = 2 ; System . out . println ( getcount ( N + 1 , K ) ) ; } }