

- 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
Binary Number with Alternating Bits in C++
Suppose we have a positive integer, we have to check whether it has alternating bits − so, two adjacent bits will always have different values.
So, if the input is like 10, then the output will be True, as binary representation of 10 is 1010.
To solve this, we will follow these steps −
- p := n AND 1
- if n < 2, then −
- return true
- n := n/2
- while n is non-zero, do −
- c := n AND 1
- if c XOR p is same as 0, then −
- return false
- p := c
- n := n/2
- return true
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: bool hasAlternatingBits(int n) { bool p=n&1; bool c; if(n<2) return true; n>>=1; while(n){ c=n&1; if(c^p==0) return false; p=c; n>>=1; } return true; } }; main(){ Solution ob; cout << (ob.hasAlternatingBits(10)); }
Input
10
Output
1
- Related Questions & Answers
- Are bits alternating in integer using JavaScript?
- Prime Number of Set Bits in Binary Representation in C++
- Prime Number of Set Bits in Binary Representation in Python
- Find the Number of 1 Bits in a large Binary Number in C++
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Next higher number with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- Minimum swaps required to make a binary string alternating in C++
- Shortest Path with Alternating Colors in Python
- Program to traverse binary tree level wise in alternating way in Python
- Count binary strings with k times appearing adjacent two set bits in C++
- Number of 1 Bits in Python
- Program to find minimum changes required for alternating binary string in Python
- Merge two arrays with alternating Values in JavaScript
- Print the number of set bits in each node of a Binary Tree in C++ Programming.
Advertisements