Given two positive integers A and B, we can change at most K bits in both the numbers to make OR of them equal to a given target number T. In the case of multiple solutions try to keep A as small as possible.
Input : A = 175, B = 66, T = 100, K = 5 Output : A = 36 B = 64 Initial bits of A = 1010 1111 Changed bits of A = 0010 0100 Initial bits of B = 0100 0010 Changed bits of B = 0100 0000 OR of changed Bits = 0110 0100 Which has decimal value equal to Target T. Input : A = 175, B = 66, T = 100, K = 4 Output : Not Possible It is not possible to get OR of A and B as T, just by changing K bits.
We can solve this problem by iterating over all bits of A and B and greedily changing them that is,
- If i-th bit of Target T is 0 then set i-th bits of A and B to 0 (if not already)
- If i-th bit of Target T is 1 then we will try to set one of the bits to 1 and we will change i-th bit of B only to 1(if not already) to minimize A.
After above procedure, if changed bits are more than K, then it is not possible to get OR of A and B as T by changing at most K bits.
If changed bits are less than k, then we can further minimize the value of A by using remaining value of K for which we will loop over bits one more time and if at any time,
- i-th A bit is 1 and i-th B bit is 0 then we will make 2 changes and flip both.
- i-th A and B bits are 1 then again we will make 1 change and flip A’s bit.
Total time complexity of above solution will be O(max number of bits).
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Write an Efficient C Program to Reverse Bits of a Number
- Count set bits in an integer
- Count number of bits to be flipped to convert A to B
- Rotate bits of a number
- Next higher number with same number of set bits
- Program to count number of set bits in an (big) array
- Count total set bits in all numbers from 1 to n
- Swap bits in a given number
- Swap all odd and even bits
- Toggle all the bits of a number except k-th bit.
- Copy set bits in a range
- Print first n numbers with exactly two set bits
- Check if bits of a number has count of consecutive set bits in increasing order
- Check if a number has bits in alternate pattern | Set 1
- Count minimum bits to flip such that XOR of A and B equal to C
Improved By : jit_t