Given an integer N which can be represented in 32 bit, the task is to find another integer X that has at most K bits set in its binary representation and bitwise AND of X and N is maximum.
Input: N = 5, K = 1
Output: X = 2
Binary representation of 5 is 101, the possible value of X such that it maximize the AND is 2
5 -> 101
2 -> 100
AND sum -> 100 (2)
4 is the maximum AND sum we can get with N and X.
Input: N = 10, K = 2
Output: X = 10
Binary representation of 10 is 1010, X = 10 possible integer to given maximum AND sum with N with atmost 2 bit set.
10 -> 1010
10 -> 1010
AND sum -> 1010 (10)
10 is the maximum AND sum we can get with N and X.
Naive Approach: A naive solution is to run a loop from 1 to N and take bitwise AND with N, and also check if the number of set bits is less than or equal to K. During each iteration maintain the maximum value of bitwise AND.
Time Complexity: O(N)
Efficient Approach: This problem can be solved efficiently by using a Greedy approach on bits. Since N can have at most 32 bits. So we will start traversing from the Most Significant bit and check if it is set(or 1) in N, if it is not set then there is no need to set this bit because AND operation will make it zero in the final answer, else we will set it in our required answer. Also, we will maintain the count of set bits in each iteration and check if it does not exceed K.
Time Complexity: O(32)
Below is the implementation of the above efficient approach :
- Time complexity: O(32)
- Auxiliary Space: O(1
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.