Absolute Value with Math.abs()
Write a Java function that takes an integer and returns its absolute value using Math.abs(). The absolute value is the non-negative value of a number without regard to its sign.
Math.abs() is a static method in Java's Math class that returns the absolute value of an int, long, float, or double argument. For int arguments, if the argument is Integer.MIN_VALUE (-2147483648), the result is that same negative value because the positive equivalent (2147483648) exceeds the int range. This is a known edge case in Java's Math.abs().
The Math class in Java provides a comprehensive set of mathematical functions: abs(), min(), max(), pow(), sqrt(), sin(), cos(), random(), and many more. All methods are static and can be called directly without creating a Math instance. Math is declared as a final class with a private constructor.
Time complexity is O(1). Space complexity is O(1). Math.abs() compiles to a single CPU instruction on most architectures, making it extremely fast.
Edge cases include zero (absolute value is 0), positive numbers (unchanged), negative numbers (become positive), and Integer.MIN_VALUE (returns itself, not positive).
Example Input & Output
Positive unchanged
Absolute of -1 is 1
Zero absolute is 0
Positive stays same
Absolute of -5 is 5
Algorithm Flow
Solution Approach
Compute the absolute value of an integer using Math.abs(). The absolute value is the non-negative magnitude of the number, discarding its sign. For positive numbers and zero, the value is unchanged. For negative numbers, the sign is inverted to positive.
Math.abs() returns the absolute value. For Integer.MIN_VALUE, the absolute value cannot be represented as a positive int, so it wraps back to negative. Use long for safety with extreme values.
Time O(1), Space O(1).
Best Answers
class Solution {
public int solution(int n) {
return Math.abs(n);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
