![]() |
VOOZH | about |
Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i.
Examples :
Input : N = 5
Output : 0, 1, 4, 5
Explanation: 0 & 5 = 0
1 & 5 = 1
2 & 5 = 0
3 & 5 = 1
4 & 5 = 4
5 & 5 = 5
So we get 0, 1, 4 and 5 in the
bitwise subsets of N.
Input : N = 9
Output : 0, 1, 8, 9
Simple Approach: A naive approach is to iterate from all numbers from 0 to N and check if (N&i == i). Print the numbers which satisfy the specified condition.
Below is the implementation of above idea:
0 1 8 9
Time Complexity : O(N)
Efficient Solution: An efficient solution is to use bitwise operators to find the subsets. Instead of iterating for every i, we can simply iterate for the bitwise subsets only. Iterating backward for i=(i-1)&n gives us every bitwise subset, where i starts from n and ends at 1.
Below is the implementation of above idea:
9 8 1 0
Output :
9 8 1 0
Time Complexity: O(K), where K is the number of bitwise subsets of N.
Steps:
0 1 4 5
Time Complexity: O(log N)
Auxiliary Space: O(2^log N)