Given a number N, check if it is positive, negative or zero without using conditional statements.
Input : 30 Output : 30 is positive Input : -20 Output : -20 is negative Input: 0 Output: 0 is zero
The signed shift n>>31 converts every negative number into -1 and every other into 0.
When we do a -n>>31, if it is a positive number then it will return -1 as we are doing -n>>31 and the vice versa when we do for a negative number.
But when we do for 0 then n>>31 and -n>>31 both returns 0, so we get a formula:
1 + (n>>31) – (-n>>31)
..1) when n is negative :
..2) when n is positive:
..3) when n is 0:
So we know it returns 0 when it is a negative number, it returns 1 when it is zero, returns 2 when it is a positive number.
So to not use if statements we store at 0th index “negative”, 1st index “zero” and at 2nd index “positive”, and print according to it.
30 is positive -20 is negative 0 is zero
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Partition negative and positive without comparison with 0
- Operators in C | Set 2 (Relational and Logical Operators)
- Sum of consecutive bit differences of first N non-negative integers
- Check if a number is multiple of 9 using bitwise operators
- Check if a number is divisible by 17 using bitwise operators
- Check if a number is divisible by 8 using bitwise operators
- Check if a Number is Odd or Even using Bitwise Operators
- Inserting m into n such that m starts at bit j and ends at bit i.
- Inserting M into N such that m starts at bit j and ends at bit i | Set-2
- Minimum bit flips such that every K consecutive bits contain at least one set bit
- Check whether bitwise AND of a number with any subset of an array is zero or not
- Check if the Xor of the frequency of all digits of a number N is zero or not
- Check if two numbers are equal without using arithmetic and comparison operators
- Check if two numbers are equal without using comparison operators
- Check if n is divisible by power of 2 without using arithmetic operators
- Multiply a number by 15 without using * and / operators
- Count trailing zero bits using lookup table
- Number of unique triplets whose XOR is zero
- Number of ways to reach the end of matrix with non-zero AND value
- Add two numbers without using arithmetic operators
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : jit_t