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
def findK ( n , k ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT pos = n // 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT pos = ( n // 2 ) + 1 ; NEW_LINE DEDENT if ( k <= pos ) : NEW_LINE INDENT return ( k * 2 - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( k - pos ) * 2 ) ; NEW_LINE DEDENT DEDENT def countSetBits ( n , k ) : NEW_LINE INDENT kth = findK ( n , k ) ; NEW_LINE return bin ( kth ) . count ( '1' ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 18 ; k = 12 ; NEW_LINE print ( countSetBits ( n , k ) ) ; NEW_LINE DEDENT