問題
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.
制約
-1,000,000,000 ≤ n ≤ 1,000,000,000
例
例 1
入力:
n = -42
期待される出力:
expected = 42
入力:
long long n = -42;
期待される出力:
long long expected = 42;
入力:
long n = -42;
期待される出力:
long expected = 42;
解説
-42 is negative, so the answer is 42.
例 2
入力:
n = 15
期待される出力:
expected = 15
入力:
long long n = 15;
期待される出力:
long long expected = 15;
入力:
long n = 15;
期待される出力:
long expected = 15;
解説
15 is already positive, so it stays 15.
解き方のヒント
まずは自分で考えてから、ヒントを1つずつ開いてみましょう。
ヒント 1
A number is unchanged if it is already nonnegative.
ヒント 2
Only negative values need to be flipped to their opposite.
ヒント 3
Zero should stay zero, so treat it with the nonnegative case.
目安の計算量
O(1) time, O(1) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。