- 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 numbers having first and last bits as the only set bits

The task is to print the given n number which have exactly two set bits that neither less than 2 nor more than 2.

Set bits in computer language are the one that have value 1 and unset bits have value as 0

Input: value of num=5 Output: 1 3 5 As 1 is equivalent to 1 in binary 3 is equivalent to 11 in binary 5 is equivalent to 101 in binary

## Algorithm

START Step 1 -> declare variable as unsigned int num=5 and int i=1 Step 2 -> print i Step 3 -> Loop For i=3 and i<=num and ++i IF (!(i-1 & i-2)) Print i End End STOP

## Example

#include <stdio.h> int main(int argc, char const *argv[]) { unsigned int num = 5; int i = 1; printf("%d ", i); //printing first number 1 for (i = 3; i <= num; ++i) { if(!(i-1 & i-2)) //performing and operation on i-1 and i-2 printf("%d ", i); } return 0; }

## Output

if we run the above program then it will generate the following output

1 3 5

- Related Questions & Answers
- Check whether the number has only first and last bits set in Python
- First and Last Three Bits in C++
- Previous smaller integer having one less number of set bits in C++
- Next greater integer having one more number of set bits in C++
- Largest number less than X having at most K set bits in C++
- Find the number with set bits only between L-th and R-th index using C++
- Count of divisors having more set bits than quotient on dividing N in C++
- Count set bits using Python List comprehension
- Python Count set bits in a range?
- 8085 Program to Multiply two 8 bits numbers
- Add two unsigned numbers using bits in C++.
- Maximum sum by adding numbers with same number of set bits in C++
- Copy set bits in a range in C++
- Count set bits in an integer in C++
- Count set bits in a range in C++

Advertisements