Number Sign Classification
Problem
Print positive if the number is greater than 0, negative if it is less than 0 and zero if it is 0.
Constraints
- -2^63 < n < 2^63
Examples
Input
-8
Output
negative
Solutions
Three cases do not overlap, so an if chain with early returns is enough.
/*
* Problem : Sign of a number.
* Input : One integer.
* Output : positive, negative or zero.
* Approach: If chain.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(long n) {
// Step 1: Check the three cases one after another.
if (n > 0) {
return "positive";
}
if (n < 0) {
return "negative";
}
return "zero";
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (2)
- Is zero positive?
- Why do we need no else?