isPositive
- return true
if x > 0
, otherwise false
Example: isPositive(-1)
Legal ops:
You have another option here:
int is_positive = (0&x^((0^x)&-(0<x)));
It is just a (0 & min(0,x)).
Test here
if your working with a number system that uses the MSB as the signage bit, you can do:
int IsPositive(int x)
{
return (((x >> 31) & 1) ^ 1) ^ !x;
}
Let's play with the sign bit: sign(~n)
: 1 if n >= 0
To get rid of the case when n
is 0: sign(~n + 1)
: 1 if n > 0 or n = MIN_INT
So, we want the case when both functions return 1:
return ((~n & (~n + 1)) >> 31) & 1;
int isPositive(int x)
{
return (!(x & 0x80000000) & !!x);
}
Why not use XOR (^)
?
Try this,
{
return ((x>>31)&1)^(!!x);
}
It can deal with the 0 case well.
int isPositive(int x) {
return !((x&(1<<31)) | !x);
}
x&(1<<31
is to check if the number is negative.
!x
is to check if the number is zero.
A number is positive if it's not negative and not zero.