Minimum integer with at most K bits set such that their bitwise AND with N is maximum | C ++ 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 significantif 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_max ( int n , int k ) { bitset < 32 > X ( 0 ) ; int cnt = 0 ; for ( int i = 31 ; i >= 0 && cnt != k ; i -- ) { if ( n & ( 1 << i ) ) { X [ i ] = 1 ; cnt ++ ; } } return X . to_ulong ( ) ; } int main ( ) { int n = 10 , k = 2 ; cout << find_max ( n , k ) << endl ; return 0 ; }