Minimum integer with at most K bits set such that their bitwise AND with N is maximum | Java program for the above approach ; 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
import java . util . * ; import java . lang . * ; class GFG { static int find_max ( int n , int k ) { int [ ] X = new int [ 32 ] ; int cnt = 0 ; for ( int i = 31 ; i >= 0 && cnt != k ; i -- ) { if ( ( n & ( 1 << i ) ) != 0 ) { X [ i ] = 1 ; cnt ++ ; } } String s = " " ; for ( int i = 31 ; i >= 0 ; i -- ) s += X [ i ] == 0 ? '0' : '1' ; return Integer . parseInt ( s , 2 ) ; } public static void main ( String [ ] args ) { int n = 10 , k = 2 ; System . out . println ( find_max ( n , k ) ) ; } }