Given an integer n, find the largest possible set of non negative integers with bitwise OR equal to n.
Input : n = 5 Output : arr = [0, 1, 4, 5] The bitwise OR of 0, 1, 4 and 5 equals 5. It is not possible to obtain a set larger than this. Input : n = 8 Output : arr = [0, 8]
Prerequisite: Maximum subset with bitwise OR equal to k
The difference in the above referenced article and this post is the number of elements to be checked. In the above referenced article, we have an array of n numbers and in this post, we have the entire set of non negative numbers.
Traversing an array was simple with the time complexity of O(N), but traversing the boundless set of non negative numbers is not possible. So how do we limit ourselves to a smaller set of numbers?
The answer lies in the concept used. For any number, x greater than n, the bitwise OR of x and n will never be equal to n.
Hence we only need to traverse from 0 to n to obtain our answer.
The second difference is that there will always be an answer for this question. On the other hand, there was no certainty in the existence of an answer in the above referenced article. This is because we can always include n in the resulting set.
Traverse the numbers from 0 to n, checking its bitwise OR with n. If the bitwise OR equals n, then include that number in the resulting set.
0 1 4 5
Time complexity: O(N)
- Numbers whose bitwise OR and sum with N are equal
- Maximum subset with bitwise OR equal to k
- Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs
- Find subsequences with maximum Bitwise AND and Bitwise OR
- Bitwise Operators in C/C++
- Bitwise and (or &) of a range
- Sum of bitwise OR of all subarrays
- Sum of bitwise AND of all possible subsets of given set
- Sum of bitwise AND of all submatrices
- Sum of Bitwise-OR of all Submatrices
- Sum of bitwise OR of all possible subsets of given set
- Bitwise Sieve
- Sum of bitwise AND of all subarrays
- Bitwise OR (or | ) of a range
- Print bitwise AND set of a number N
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.