Count set bits in the Kth number after segregating even and odd from N natural numbers | 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
function findK ( n , k ) { let pos ; if ( n % 2 == 0 ) { pos = parseInt ( n / 2 , 10 ) ; } else { pos = parseInt ( n / 2 , 10 ) + 1 ; } if ( k <= pos ) { return ( k * 2 - 1 ) ; } else { return ( ( k - pos ) * 2 ) ; } } function countSetBits ( n , k ) { let kth = findK ( n , k ) ; let count = 0 ; while ( kth > 0 ) { count += kth & 1 ; kth >>= 1 ; } return count ; } let n = 18 , k = 12 ; document . write ( countSetBits ( n , k ) ) ;