Đề bài
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.
Ràng buộc
-1,000,000,000 ≤ n ≤ 1,000,000,000
Ví dụ
Đầu vào:
n = -42
Kết quả mong đợi:
expected = 42
Đầu vào:
long long n = -42;
Kết quả mong đợi:
long long expected = 42;
Đầu vào:
long n = -42;
Kết quả mong đợi:
long expected = 42;
Giải thích
-42 is negative, so the answer is 42.
Đầu vào:
n = 15
Kết quả mong đợi:
expected = 15
Đầu vào:
long long n = 15;
Kết quả mong đợi:
long long expected = 15;
Đầu vào:
long n = 15;
Kết quả mong đợi:
long expected = 15;
Giải thích
15 is already positive, so it stays 15.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
A number is unchanged if it is already nonnegative.
Gợi ý 2
Only negative values need to be flipped to their opposite.
Gợi ý 3
Zero should stay zero, so treat it with the nonnegative case.
Độ phức tạp mong đợi
O(1) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.