VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-bitwise-and-set-of-a-number-n/

⇱ Print bitwise AND set of a number N - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print bitwise AND set of a number N

Last Updated : 2 Aug, 2023

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:  


Output
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:  


Output
9 8 1 0

Output :

9 8 1 0


Time Complexity: O(K), where K is the number of bitwise subsets of N.

Approach: Optimized Bit Manipulation

Steps:

  1. Initialize an empty list res with 0 as the first element.
  2. Initialize a variable x as 1.
  3. While x is less than or equal to N, do the following:
    a. If the x-th bit of N is 1, then for each element r in res, append r | x to res.
    b. Multiply x by 2.
  4. Return the final list res.

Output
0 1 4 5 

Time Complexity: O(log N)
Auxiliary Space: O(2^log N)

Comment
Article Tags: