+ 3
How to identify a integer number is +ve or - ve without if-else
11 Antworten
+ 5
cout << (unsigned(a) <= unsigned(-1)/2 ? "+" : "-") << endl;
For any int a.
If you dont want to use any conditional:
bool isPositive = unsigned(a) <= unsigned(-1)/2;
+ 3
you can do it with switch case also
+ 1
the first bit of any variable of basic signed datatype represents the sign
+ 1
Not first bit, last bit MSB represents sign and then how to write program
+ 1
is it the left-most bit you are referring to in a binart number?
+ 1
i want without / % operators
+ 1
conditional expression ? : equivalent to if-else
+ 1
#include <limits.h>
int main() {
int a = -9;
bool isPositive = unsigned(a) <= INT_MAX;
return 0;
}
+ 1
using relation operator in a statement is similar to if-else
<= will generate if-else condition
+ 1
int a = -1;
bool isPositive = ~a & (1 << 8*sizeof(a) - 1);
I hard coded the number 0x1f (31) and i dont like that because ints can be other size than 32 bits but I think this will do it.
Edit:
Corrected.
0
use sizeof operator to identify int size