Problem:
What is an efficient way to find the sign of a number in Java?
Solution:
To find the sign of a number, you can use the signum() function. (e.g. Math.signum(), Integer.signum(), Long.signum(), etc.)
For example:
int sign1 = (int) Math.signum(-123); // -1
int sign2 = (int) Math.signum(222); // 1
int sign3 = Integer.signum(-1234); // -1
double sign4 = Math.signum(-123.0); // -1.0
float sign5 = Math.signum(111.0f); // 1.0f
double sign6 = Math.signum(0.0); // 0.0
Notes:
For more information (minimum JDK version, etc.), check out the references below.
No comments:
Post a Comment