Count integers less than A so that Bitwise AND of B with XOR of A and the number is 0
Given two positive integers A and B, the task is to find the number of integers X such that (A⊕X ) & B = 0 and 0 ≤ X < A where ⊕ is bitwise XOR and & is bitwise AND operator.
Input: A = 3, B = 5
Explanation: Here A = 3, B = 5. So we need to find the number of X,
which satisfy 0≤X<3, and (3⊕X)&5=0.
( 011 ⊕ 000 ) & 101 = 011 & 101 = 001 ≠ 0
( 011 ⊕ 001 ) & 101 = 010 & 101 = 000
( 011 ⊕ 010 ) & 101 = 001 & 101 = 001 ≠ 0
So, X = 1 only satisfies the requirements. So the answer is 1.
Input: A = 8, B = 4
Approach: The idea to solve this problem is:
The bitwise and of A⊕X with B should be 0.
- This means if a bit is set in B, it will be set in X if and only if it is set in A. In other words, if some bit of B is set, there is exactly one choice for such a bit in X.
- After this, we apply a classical technique when counting things that must be lexicographically smaller than something else. Iterate over the positions, and fix the one that is the first to be strictly less, then we have complete freedom in all following positions.
- That is, iterate bits from 30 down to 0. Suppose we are currently at the ith bit. We will assume that the bits from 30 to (i+1) of both A and X are equal, and the ith bit of X is strictly less than the ith bit of A (\this is only possible when the i-th bit of A is 1, and the ith bit of B is not 1).
- Now, bits 0 to i−1 are totally free (except for the restriction on set bits of B), and each of these have 2 choices. So, if there are c such free bits, add 2c to the answer.
Follow the given steps to solve the problem:
- Iterate from i = 30 to 1.
- If the ith bit is either set in B or not set in A, do nothing
- Otherwise, count the number of bits from 0 to i−1 that are not set in B. If this number is c, add 2c to the answer.
Below is the implementation of the above approach.
Time Complexity: O(logN)
Auxiliary Space: O(1)