- 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
Check if a number has two adjacent set bits in C++
Here we will see, if a number has adjacent set bits in its binary representation. Suppose the number 12 has two consecutive 1s (12 = 1100).
To check this type of number, the idea is very simple. We will shift the number 1 bit, then do bitwise AND. If the bitwise AND result is non-zero, then there must be some consecutive 1s.
Example
#include <iostream> using namespace std; bool hasConsecutiveOnes(int n) { if((n & (n >> 1)) == 1){ return true; }else{ return false; } } int main() { int num = 67; //1000011 if(hasConsecutiveOnes(num)){ cout << "Has Consecutive 1s"; }else{ cout << "Has No Consecutive 1s"; } }
Output
Has Consecutive 1s
Advertisements