- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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
Advertisements