Check Whether a Number Is Positive, Negative, or Zero
Solve this ProblemEasy5 min
Topics
BasicsConditionals
Companies
TCSInfosysWipro
Given an integer
n, determine whether it is positive, negative, or exactly zero, and return one of the strings "Positive", "Negative", or "Zero".
This is the simplest possible introduction to multi-way branching: three mutually exclusive outcomes, decided by comparing a single value against 0. The if-else chainIf-Else ChainA sequence of if / else-if / else blocks, tried in order until one condition matches. version spells out each condition explicitly, which is the clearest way to learn the pattern. The ternaryTernary OperatorThe condition ? valueIfTrue : valueIfFalse expression — a compact, single-line alternative to a short if-else. version nests the same two comparisons into a single expression once that pattern feels natural.
Test Case 1:
Input:n = 7
Output:Positive
Explanation:7 is greater than 0.
Test Case 2:
Input:n = -4
Output:Negative
Explanation:-4 is less than 0.
Test Case 3:
Input:n = 0
Output:Zero
Explanation:0 is neither greater than nor less than 0.
Constraints
- ◆
-1000 ≤ n ≤ 1000
Try the Dry Run
Approach & Solutions
If-Else ChainGood
Check the conditions one at a time, in order: if n is greater than 0 it's positive; otherwise, if it's less than 0 it's negative; anything left over must be exactly 0. Only one branch ever runs, and the logic reads top to bottom exactly the way you'd explain it out loud.
Time
O(1)Space
O(1)Java
1class Solution {
2 public String checkNumberSign(int n) {
3 if (n > 0) {
4 return "Positive";
5 } else if (n < 0) {
6 return "Negative";
7 } else {
8 return "Zero";
9 }
10 }
11}Nested Ternary OperatorOptimal
The exact same three-way decision, written as a single expression: n > 0 picks "Positive"; otherwise a second ternary checks n < 0 for "Negative", falling back to "Zero". Same branches, same result — just compacted into one line once the if-else version feels familiar.
Time
O(1)Space
O(1)Java
1class Solution {
2 public String checkNumberSign(int n) {
3 return n > 0 ? "Positive" : (n < 0 ? "Negative" : "Zero");
4 }
5}