
- 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
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 Articles
- 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++
- Count binary strings with k times appearing adjacent two set bits in C++
- Minimum swaps required to make a binary string alternating in C++
- Program to traverse binary tree level wise in alternating way in Python
- Print the number of set bits in each node of a Binary Tree in C++ Programming.
- Program to find minimum changes required for alternating binary string in Python
- Shortest Path with Alternating Colors in Python
- Maximum number of contiguous array elements with same number of set bits in C++
- Number of 1 Bits in Python

Advertisements