

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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
- Related Questions & Answers
- How to check if a number is positive, negative or zero using Python?
- C program to Check Whether a Number is Positive or Negative or Zero?
- Program to check if a number is Positive, Negative, Odd, Even, Zero?
- C# Program to check if a number is Positive, Negative, Odd, Even, Zero
- Python Program to Check if a Number is Positive, Negative or 0
- Java Program to Check Whether a Number is Positive or Negative
- Check whether product of integers from a to b is positive, negative or zero in Python
- Java program to find if the given number is positive or negative
- Sum a negative number (negative and positive digits) - JavaScript
- Check if a number is multiple of 5 without using / and % operators in C++
- Finding array number that have no matching positive or negative number in the array using JavaScript
- Check if a number is a Krishnamurthy Number or not in C++
- How to Check if a Number is Odd or Even using Python?
- Check if a number is jumbled or not in C++
- Check if input is a number or letter in JavaScript?
Advertisements