Count numbers less than N whose Bitwise AND with N is zero
Given a positive integer N, the task is to count all numbers which are less than N and Bitwise AND of all such numbers with N is zero.
Input: N = 5
The integers less than N(= 5) whose Bitwise AND with 5 is 0 are 0 and 2. Hence, the total count is 2.
Input: N = 9
Approach: The given problem can be solved based on the observation that all bits which are set in N will be unset in any number which has Bitwise AND with N equal to 0. Follow the steps below to solve the problem:
- Initialize a variable, say unsetBits, equal to the total number of unset bits in the given integer N.
- Now, every unset bit in N can have either 0 or 1 in the corresponding position, as the Bitwise AND for any position where N has an unset bit will always be equal to 0. Hence, the total number of different possibilities will be 2 raised to the power of unsetBits.
- Therefore, print the value of 2 to the power of unsetBits as the result.
Below is the implementation of the above approach:
Time Complexity: O(log N)
Auxiliary Space: 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.