Check if a number is positive, negative or zero using bit operators in C++

C++Server Side ProgrammingProgramming

Here we will check whether a number is positive, or negative or zero using bit operators. If we perform shifting like n >> 31, then it will convert every negative number to -1, every other number to 0. If we perform –n >> 31, then for positive number it will return -1. When we do for 0, then n >> 31, and –n >> 31, both returns 0. for that we will use another formula as below −

1+(𝑛>>31)−(−𝑛>>31)

So now, if

  • n is negative: 1 + (-1) – 0 = 0
  • n is positive: 1 + 0 – (-1) = 2
  • n is 0: 1 + 0 – 0 = 1

Example

 Live Demo

#include <iostream>
#include <cmath>
using namespace std;
int checkNumber(int n){
   return 1+(n >> 31) - (-n >> 31);
}
int printNumberType(int n){
   int res = checkNumber(n);
   if(res == 0)
      cout << n << " is negative"<< endl;
   else if(res == 1)
      cout << n << " is Zero" << endl;
   else if(res == 2)
      cout << n << " is Positive" << endl;
}
int main() {
   printNumberType(50);
   printNumberType(-10);
   printNumberType(70);
   printNumberType(0);
}

Output

50 is Positive
-10 is negative
70 is Positive
0 is Zero
raja
Published on 22-Oct-2019 09:57:42
Advertisements