Open In App

Count values whose Bitwise OR with A is equal to B

Given two integers A and B, the task is to count possible values of X that satisfies the condition A | X = B. Note: | represents Bitwise OR operation.

Examples:

Input: A = 2, B = 3
Output: 2
Explanation: Since, 2 | 1 = 3 and 2 | 3 = 3. Therefore, the possible values of x are 1 and 3.



Input: A = 5, B = 7
Output: 4

Naive Approach: The simplest approach to solve this problem is to iterate over the range [1, B] and check for every number, whether its Bitwise OR with A is equal to B. If the condition is satisfied, increment the count. Time Complexity: O(b)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized based on the following observations:




Article Tags :