Problem
The absolute value of a number is its distance from zero. Compute it with an if statement instead of a built-in abs function.
Implement absolute_value(n).
Input
n: Any integer.
Output
Return n if it is zero or positive, otherwise -n.
Constraints
-1,000,000,000 ≤ n ≤ 1,000,000,000
Examples
Input:
n = -42
Expected output:
expected = 42
Input:
long long n = -42;
Expected output:
long long expected = 42;
Input:
long n = -42;
Expected output:
long expected = 42;
Explanation
-42 is negative, so the answer is 42.
Input:
n = 15
Expected output:
expected = 15
Input:
long long n = 15;
Expected output:
long long expected = 15;
Input:
long n = 15;
Expected output:
long expected = 15;
Explanation
15 is already positive, so it stays 15.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
A number is unchanged if it is already nonnegative.
Hint 2
Only negative values need to be flipped to their opposite.
Hint 3
Zero should stay zero, so treat it with the nonnegative case.
Expected complexity
O(1) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.