Given two positive integers A and B. Let’s define D such that B AND D = D. The task is to maximize the expression A XOR D.
Input: A = 11 B = 4 Output: 15 Take D = 4 as (B AND D) = (4 AND 4) = 4. Also, (A XOR D) = (11 XOR 4) = 15 which is the maximum according to the given condition. Input: A = 9 and B = 13 Output: 13
Naive approach: Since B AND D = D, D will always be smaller than or equal to B. Hence, one can run a loop from 1 to B and check whether the given conditions are satisfied or not.
Efficient approach: Instead of running a loop and checking for each D, the maximum value of the expression (A XOR D) can be easily calculated using Bit Manipulation techniques.
Let’s take an example to understand the way to approach the problem:
A = 11 = 1011, B = 14 = 1110 Let's assume D = abcd in base 2 notation B AND D: 1110 A XOR D: 1011 abcd abcd ------ ------ abcd ???? At 0th place: (0 AND d) = d implies d = 0 At 1st place: (1 AND c) = c implies c = 0, 1 but to maximize (A XOR D), take c = 0 At 2nd place: (1 AND b) = b implies b = 0, 1 but to maximize (A XOR D), take b = 1 At 3rd place: (1 AND a) = a implies a = 0, 1 but to maximize (A XOR D), take a = 0 Hence, D = 0100 = 4 and maximum value of (A XOR D) = (11 XOR 4) = 15.
Below is the implementation of the above approach:
- Maximize the expression (A AND X) * (B AND X) | Bit Manipulation
- Bit manipulation | Swap Endianness of a number
- Winner in the Rock-Paper-Scissor game using Bit manipulation
- Fast Exponention using Bit Manipulation
- Bits manipulation (Important tactics)
- Inserting m into n such that m starts at bit j and ends at bit i.
- Inserting M into N such that m starts at bit j and ends at bit i | Set-2
- Count of 1-bit and 2-bit characters in the given binary string
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Print the balanced bracket expression using given brackets
- Find minimum value of the expression by choosing K elements from given array
- Find the minimum value of the given expression over all pairs of the array
- Maximize a given unsigned number number by swapping bits at it's extreme positions.
- Minimum flips required to maximize a number with k set bits
- Maximize the number by rearranging bits
- Maximize the bitwise OR of an array
- Maximize the number of segments of length p, q and r
- Maximize the total profit of all the persons
- Burst Balloon to maximize coins
- Maximize the product of four factors of a Number
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.