Maximum value of B less than A such that A ^ B = A + B
Given an integer A, the task is to find the maximum value possible(B) which is less than A, such that xor of these two numbers A and B are equal to their sum, that is A ^ B = A + B.
Input: A = 4
There are many such integers, such that A ^ B = A + B
Some of these integers are –
4 ^ 3 = 4 + 3 = 7
4 ^ 2 = 4 + 2 = 6
4 ^ 1 = 4 + 1 = 5
4 ^ 0 = 4 + 0 = 4
The maximum of these values is 3
There is no integer except 0 such that A + B = A ^ B
Approach: The idea is to use the fact that
and to get the value of , the value of (A & B) must be equal to 0.
=> A & B = 0 => B = ~A
A = 4 (1 0 0) B = ~ A = (0 1 1) = 3
Below is the implementation of the above approach:
- Time Complexity: In the above-given approach, there is the conversion from decimal to binary which takes O(logN) time in the worst case. Therefore, the time complexity for this approach will be O(logN).
- Auxiliary Space Complexity: In the above-given approach, there is no extra space used. Therefore, the auxiliary space complexity for the above approach will be O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.