Positive, Negative or Zero
Problem
Read one integer and print Positive if it is greater than 0, Negative if it is less than 0, and Zero if it is 0.
Constraints
- -10^9 <= n <= 10^9
Examples
Input
5
Output
Positive
Input
-2
Output
Negative
Solutions
Three cases cover all integers. We must handle 0 separately, because it is not positive and not negative.
/*
* Problem : Classify a number by its sign.
* Input : One integer.
* Output : Positive, Negative or Zero.
* Approach: Compare the number with 0.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int number = new Scanner(System.in).nextInt();
// Step 1: If the number is greater than 0, it is positive.
if (number > 0) {
System.out.println("Positive");
// Step 2: If the number is less than 0, it is negative.
} else if (number < 0) {
System.out.println("Negative");
// Step 3: In all other cases the number is 0. Zero is neither positive nor negative.
} else {
System.out.println("Zero");
}
}
}
Hints (2)
- How many different answers are possible?
- Do not forget zero.