Minimum integer with at most K bits set such that their bitwise AND with N is maximum | Function to find the integer with maximum bitwise with N ; Store answer in the bitset Initialized with 0 ; To maintain the count of set bits that should exceed k ; Start traversing from the Most significant if that bit is set in n then we will set in our answer i . e in X ; Checking if the ith bit is set in n or not ; Converting into integer ; Driver code ; Function Call
def find_max ( n , k ) : NEW_LINE INDENT X = [ 0 ] * 32 NEW_LINE cnt = 0 NEW_LINE i = 31 NEW_LINE while ( i >= 0 and cnt != k ) : NEW_LINE INDENT if ( ( n & ( 1 << i ) ) != 0 ) : NEW_LINE INDENT X [ i ] = 1 NEW_LINE cnt += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT s = " " NEW_LINE for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT if X [ i ] == 0 : NEW_LINE INDENT s += '0' NEW_LINE DEDENT else : NEW_LINE INDENT s += '1' NEW_LINE DEDENT DEDENT return int ( s , 2 ) NEW_LINE DEDENT n , k = 10 , 2 NEW_LINE print ( find_max ( n , k ) ) NEW_LINE