
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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
Advertisements