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 function ; Function Call
function find_max ( n , k ) { var X = Array . from ( { length : 32 } , ( _ , i ) => 0 ) ; var cnt = 0 ; for ( i = 31 ; i >= 0 && cnt != k ; i -- ) { if ( ( n & ( 1 << i ) ) != 0 ) { X [ i ] = 1 ; cnt ++ ; } } var s = " " ; for ( i = 31 ; i >= 0 ; i -- ) s += X [ i ] == 0 ? ' ' : ' ' ; return parseInt ( s , 2 ) ; } var n = 10 , k = 2 ; document . write ( find_max ( n , k ) ) ;