basics · beginner · ~10 min
Use `?:` for compact conditional expressions.
Implement int sign(int n) returning -1 if n < 0, 0 if n == 0, 1 if n > 0. Use the ternary operator ?:.
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.
signed int.
-1 / 0 / 1.
One line.
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.