How to check if a Number is Positive or Negative in Java - Interview Question

Write a Java program to check if a number is positive or negative is one of the popular Java coding interview question, it may look easy but programmers often fumble on this question. One of the tricky part of this question is that Java has multiple data type to support numbers like byte, short, char, int, long, float and double, out of those all are signed except char, which can not represent negative numbers. Some solution work for int and long but may not work for floating point number e.g. float and double. This is also a tricky Java question, another tricky point is considering special case like positive infinity, negative infinity or NaN in case of checking floating point numbers. Things gets more complicated when, as followup questions, interviewer put additional conditions such as you can not use relational operator etc. Nevertheless Java provides several way to check if a number whether integer or floating point is positive or negative. In this Java tutorial, we will see such methods of checking sign of number in Java.

Different ways to check if number is positive or negative in Java

Here is quick summary of different ways I can think of checking sign of number and finding whether a number is positive or negative in Java. All these method assumes that you will put special check logic for handling special cases like positive infinity, negative infinity and Nan and assuming zero on positive side.

1) By Converting Number to String
Convert any number into String and get first character, if its equals to "-" then its negative number otherwise its
positive one. Though this method will not work for float and double, if number is represented in exponential form. This could be the case if you are dealing with large floating point numbers. For long and int this method of checking sign of number should work. Look at following example of string equivalent of minimum values of Integer, Long, Float and Double

System. out. println ( Integer. MIN_VALUE ) ;
System. out. println ( Long. MIN_VALUE ) ;
System. out. println ( Float. MIN_VALUE ) ;
System. out. println ( Double. MIN_VALUE ) ;

- 2147483648
- 9223372036854775808
1.4E-45
4.9E-324

Only Integer and Long can be checked getting first character and comparing with "-". See How to convert Integer to String and Long to String in Java to convert these numbers into String. By the way this approach is fragile and should not be used in any production code, I have just shared it here because I have seen people checking sign of number like this.

2) By using Relational Operators in Java
Use relational operator to check if number is positive or not, if number >=0 means number is positive if number<0 means number is negative in Java this should work for double and float as well but I haven't tested it for all values.

public static String checkSignWithRelational ( double number ){
if ( number < 0 ){
return "negative" ;
} else {
return "positive" ;
}
}

Testing:
System. out. println ( "0.0 is " + checkSignWithRelational ( 0.0 )) ;
System. out. println ( "2.0 is " + checkSignWithRelational ( 2.0 )) ;
System. out. println ( "-2.0 is " + checkSignWithRelational (- 2.0 )) ;
System. out. println ( "Double.POSITIVE_INFINITY is " + checkSignWithRelational ( Double. POSITIVE_INFINITY )) ;
System. out. println ( "Double.NEGATIVE_INFINITY is " + checkSignWithRelational ( Double. NEGATIVE_INFINITY )) ;

Output
0.0 is positive
2.0 is positive
- 2.0 is negative
Double. POSITIVE_INFINITY is positive
Double. NEGATIVE_INFINITY is negative

In my opinion this should be the right way to check whether a number is positive or negative in Java. Let me know if you guys have seen any issue using relational operator to check sign of a number in Java.

3) By Using Bit Shift operator
This is an alternative way of checking if a number is positive or negative in Java and used if Interviewer ask you not to use relational operators. Negative numbers in Java are represented using 2's complement method and since long and int are signed integer along with byte and short, most significant bit represent sign of number which should be 0 for positive number and 1 for negative number in binary format. By using bit shift operator or a proper mask you can check if most significant bit is 1 or zero. Here is example for checking int and long values :

public static String checkSign ( int number ){
if (number == 0 ) return "positive" ;
if (number >> 31 != 0 ){
return "negative" ;
} else {
return "positive" ;
}
}

public static String checkSign ( long number ){
if (number == 0 ) return "positive" ;
if (number >> 63 != 0 ){
return "negative" ;
} else {
return "positive" ;
}
}
Testing for checkSign(int) method
System. out. println ( "0 is " + checkSign ( 0 )) ;
System. out. println ( "2 is " + checkSign ( 2 )) ;
System. out. println ( "-2 is " + checkSign (- 2 )) ;
System. out. println ( "Integer.MAX_VALUE is " + checkSign ( Integer. MAX_VALUE )) ;
System. out. println ( "Integer.MIN_VALUE is " + checkSign ( Integer. MIN_VALUE )) ;

Output
0 is positive
2 is positive
- 2 is negative
Integer. MAX_VALUE is positive
Integer. MIN_VALUE is negative

This method can be extended to check double and float value by representing double and float values into long
using Double.longBitsToDouble() or Float.floatToIntBits(number).

4) Use Math.signum()
java.lang.Math provides a method called signum() which returns signum function of method argument means returns zero if argument is zero , 1.0 if argument is greater than zero and -1.0 if argument is less than zero. This is a overloaded method to accept float and double values.

That’s all on How to check if a number is positive or negative in Java. From looking all approaches, seems using relational operator seems most easy and correct solution to find out if number is positive or negative. Don’t use String approach, its fragile and only works for some data types.


Read more: http://javarevisited.blogspot.com/2013/01/how-to-check-if-number-is-positive-or-negative-java-example.html#ixzz2khayFsla

你可能感兴趣的:(Java,Core,Tech)