The abs()
function returns the absolute value of a number, which is the number's positive value. Essentially, it measures the distance of a number from zero on the number line.
We need to create our own function abs()
that mimics this functionality without using Java's built-in abs()
function.
abs(-1.217197940) ➞ 1.21719794 abs(-544.0) ➞ 544 abs(250.3) ➞ 250.3 abs(0) ➞ 0 abs(-0.14) ➞ 0.14
To solve this problem, we need to understand the core challenge: determining whether a number is negative and converting it to its positive counterpart if it is.
We can achieve this by using a simple conditional check:
A naive solution involves checking if the number is less than zero and then converting it to positive if it is. This approach is straightforward and efficient with a time complexity of O(1).
The naive solution is already optimal for this problem since it operates in constant time O(1). There are no further optimizations needed.
public class AbsoluteValue {
// Function to return the absolute value of a number
public static double abs(double n) {
// Check if the number is negative
if (n < 0) {
// If negative, return the positive counterpart
return -n;
} else {
// If positive or zero, return the number as is
return n;
}
}
// Main method to test the abs function
public static void main(String[] args) {
System.out.println(abs(-1.217197940)); // ➞ 1.21719794
System.out.println(abs(-544.0)); // ➞ 544
System.out.println(abs(250.3)); // ➞ 250.3
System.out.println(abs(0)); // ➞ 0
System.out.println(abs(-0.14)); // ➞ 0.14
}
}
The time complexity of this solution is O(1) because it involves a single conditional check and a possible multiplication, both of which are constant-time operations.
The space complexity is also O(1) as no additional space is required beyond a few variables.
Consider the following edge cases:
abs(0) ➞ 0
abs(-0.14) ➞ 0.14
abs(-1000000) ➞ 1000000
Our algorithm handles these cases effectively by design.
To test the solution comprehensively, consider a variety of test cases:
Use a testing framework like JUnit for automated testing.
When approaching such problems:
Recreating the abs()
function is a simple yet fundamental exercise in understanding conditional logic and basic operations. Mastering such problems helps build a strong foundation in programming.