

- 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
Check if a number has bits in alternate pattern - Set 1 in C++
Let us consider we have an integer n. The problem is to check, whether this integer has alternate patterns in its binary equivalent or not. The alternate pattern means 101010….
The approach is like: check each digit using binary equivalent, and if two consecutive are same, return false, otherwise true.
Example
#include <iostream> using namespace std; bool hasAlternatePattern(unsigned int n) { int previous = n % 2; n = n/2; while (n > 0) { int current = n % 2; if (current == previous) // If current bit is same as previous return false; previous = current; n = n / 2; } return true; } int main() { unsigned int number = 42; if(hasAlternatePattern(number)) cout << "Has alternating pattern"; else cout << "Has no alternating pattern"; }
Output
Has alternating pattern
- Related Questions & Answers
- Check if a number has bits in alternate pattern - Set-2 O(1) Approach in C++
- Check if a number has two adjacent set bits in C++
- Check if a number has same number of set and unset bits 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
- Check whether the number has only first and last bits set in Python
- Check if the given decimal number has 0 and 1 digits only in Python
- Number of 1 Bits in Python
- Number of flips to make binary string alternate - Set 1 in C++
- Alternate bits of two numbers to create a new number in C++
- Check if a field of table has NOT NULL property set in SQL?
- Find the Number of 1 Bits in a large Binary Number in C++
- Check if Hashtable has a fixed size in C#
- Check if ListDictionary has a fixed size in C#
- Check if a string has white space in JavaScript?
Advertisements