M | function to find the next higher number with same number of set bits as in 'x ; the approach is same as discussed in ; function to find the mth smallest number having k number of set bits ; smallest number having ' k ' number of set bits ; finding the mth smallest number having k set bits ; required number ; Driver Code
' NEW_LINE def nxtHighWithNumOfSetBits ( x ) : NEW_LINE INDENT rightOne = 0 NEW_LINE nextHigherOneBit = 0 NEW_LINE rightOnesPattern = 0 NEW_LINE next = 0 NEW_LINE if ( x ) : NEW_LINE INDENT rightOne = x & ( - x ) NEW_LINE nextHigherOneBit = x + rightOne NEW_LINE rightOnesPattern = x ^ nextHigherOneBit NEW_LINE rightOnesPattern = ( rightOnesPattern ) // rightOne NEW_LINE rightOnesPattern >>= 2 NEW_LINE next = nextHigherOneBit | rightOnesPattern NEW_LINE DEDENT return next NEW_LINE DEDENT def mthSmallestWithKSetBits ( m , k ) : NEW_LINE INDENT num = ( 1 << k ) - 1 NEW_LINE for i in range ( 1 , m ) : NEW_LINE INDENT num = nxtHighWithNumOfSetBits ( num ) NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 6 NEW_LINE k = 4 NEW_LINE print ( mthSmallestWithKSetBits ( m , k ) ) NEW_LINE DEDENT