Check if a given number is sparse or not in C++

C++Server Side ProgrammingProgramming

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

 Live Demo

#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
raja
Published on 21-Oct-2019 09:09:58
Advertisements