
- 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 given number is sparse or not in C++
In this section, we will see how to check a number is sparse or not. A number is said to be sparse if the binary representation of the number, has no two or more than two consecutive 1s. Suppose a number is like 72. This is 01001000. Here no two or more consecutive 1s.
To check a number is sparse or not, we will take the number as n, then shift that number one bit to the right, and perform bitwise AND. if the result is 0, then that is a sparse number, otherwise not.
Example
#include <iostream> using namespace std; bool isSparseNumber(int n) { int res = n & (n >> 1); if(res == 0) return true; return false; } int main() { int num = 72; if(isSparseNumber(num)){ cout << "This is sparse number"; } else { cout << "This is not sparse number"; } }
Output
This is sparse number
- Related Articles
- Check if a given matrix is sparse or not in C++
- Check if given number is Emirp Number or not in Python
- Check if a number is in given base or not in C++
- Check if the given number is Ore number or not in Python
- Check whether a given number is Polydivisible or Not
- Swift Program to Check if the given number is Perfect number or not
- Check if a given graph is tree or not
- Check if a number is a Krishnamurthy Number or not in C++
- Check if a number is jumbled or not in C++
- Check if a given matrix is Hankel or not in C++
- Check if a number is an Unusual Number or not in C++
- Check if a number is an Achilles number or not in Python
- Check if a number is an Achilles number or not in C++
- PHP program to check if a given number is present in an infinite series or not
- Check if a number is Quartan Prime or not in C++

Advertisements