- Related Questions & Answers
- Check if a number has same number of set and unset bits in C++
- Check if a number has bits in alternate pattern - Set 1 in C++
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++
- Check if all bits of a number are set in Python
- Check whether the number has only first and last bits set in Python
- Count binary strings with k times appearing adjacent two set bits in C++
- Check if Hashtable has a fixed size in C#
- Check if ListDictionary has a fixed size in C#
- Check if a binary string has two consecutive occurrences of one everywhere in C++
- Minimum number using set bits of a given number in C++
- Check if HybridDictionary has fixed size in C#
- Check if the ArrayList has a fixed size in C#
- MySQL query to check if a certain row has only two words?
- C# program to count total set bits in a number

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

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.

#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"; } }

Has Consecutive 1s

Advertisements