- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 number is positive, negative or zero using bit operators in C++
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
#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
Advertisements