basics · beginner · ~10 min
Use `?:` for compact conditional expressions.
Return the sign of an integer as -1, 0, or 1, using the ternary (?:) operator.
Implement int sign(int n) that returns -1 when n is negative, 0 when n is zero, and 1 when n is positive. Express the three-way decision with the conditional operator ?:.
A single signed int n.
Returns -1, 0, or 1 according to the sign of n.
sign(5) -> 1
sign(-3) -> -1
sign(0) -> 0
INT_MAX returns 1 and INT_MIN returns -1.n / abs(n) — that is undefined when n is 0 (and abs(INT_MIN) is undefined).A nested ternary is the cleanest way to express a 3-way decision; recognising when it improves readability vs hurts it is a real skill.
A single signed int n.
-1, 0, or 1 according to the sign of n.
Use the ternary operator; one expression. Don't divide by n.
int sign(int n) { /* TODO */ return 0; }
Returning n / abs(n) — undefined for n == 0.
0, INT_MAX, INT_MIN.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.