Count set bits in the Kth number after segregating even and odd from N natural numbers | Java implementation of the approach ; Function to return the kth element of the Odd - Even sequence of length n ; Finding the index from where the even numbers will be stored ; Return the kth element ; Function to return the count of set bits in the kth number of the odd even sequence of length n ; Required kth number ; Return the count of set bits ; Driver code
class GFG { static int findK ( int n , int k ) { int pos ; if ( n % 2 == 0 ) { pos = n / 2 ; } else { pos = ( n / 2 ) + 1 ; } if ( k <= pos ) { return ( k * 2 - 1 ) ; } else return ( ( k - pos ) * 2 ) ; } static int countSetBits ( int n , int k ) { int kth = findK ( n , k ) ; int count = 0 ; while ( kth > 0 ) { count += kth & 1 ; kth >>= 1 ; } return count ; } public static void main ( String [ ] args ) { int n = 18 , k = 12 ; System . out . println ( countSetBits ( n , k ) ) ; } }