
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Check if a number has bits in alternate pattern - Set 1 in C++
- Check if a number has same number of set and unset bits in C++
- Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++
- Check if bits of a number has count of consecutive set bits in increasing order in Python
- Check if all bits of a number are set in Python
- Count binary strings with k times appearing adjacent two set bits in C++
- Check whether the number has only first and last bits set in Python
- Minimum number using set bits of a given number in C++
- C# program to count total set bits in a number
- Next higher number with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- How to count set bits in a floating point number in C?
- Prime Number of Set Bits in Binary Representation in C++
- Minimum flips required to maximize a number with k set bits in C++.
- For every set bit of a number toggle bits of other in C++

Advertisements