- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Print bitwise AND set of a number N in C++

In this problem, we have to print all the numbers from 0 to n which are Bitwise AND of a binary of n.

Let’s take an example to understand the concept better.

Input : N = 4. Output : 0 4 Explanation : 0 & 4 = 0 1 & 4 = 0 2 & 4 = 0 3 & 4 = 0 4 & 4 = 4. Input : N = 6 Output : 0, 2, 4, 6

To solve this problem, we need to use bitwise operators. Using these we will find the required subsets. We will iterate backward from n to 1 using a different update function that will use only those values that return are outputs of and operation of some AND with n. The operation would be **i = (i-1) & N.**

Based on this idea lets create an algorithm −

## Algorithm

Step 1 : Loop from n to 1 using decrement operator i = (i-1) & n Step 2 : PRINT i. Step 3 : EXIT.

## Example

Program implementation of the above algorithm −

#include <iostream> using namespace std; int main() { int n = 11; for (int i = n; i > 0; i = (i - 1) & n) cout << i << " "; cout << 0; return 0; }

## Output

11 10 9 8 3 2 1 0

- Related Questions & Answers
- Bitwise AND of N binary strings in C++
- Largest set with bitwise OR equal to n in C++
- Bitwise OR of N binary strings in C++
- Python Program to Read a Number n And Print the Series "1+2+…..+n= "
- Goland Program to Read a Number (n) And Print the Series "1+2+…..+n= "
- Python Program to Read a Number n and Print the Natural Numbers Summation Pattern
- Golang Program to Read a Number (n) and Print the Natural Numbers Summation Pattern
- Bitwise and (or &) of a range in C++
- Print the number of set bits in each node of a Binary Tree in C++ Programming.
- Number of pairs with Bitwise OR as Odd number in C++
- Python program to print a checkboard pattern of n*n using numpy.
- Count pairs with Bitwise AND as ODD number in C++
- Count pairs with Bitwise-AND as even number in C++
- Bitwise AND of Numbers Range in C++
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python

Advertisements