Start learning free

LESSON 82 OF 409 · CONDITIONAL STATEMENTS - CHALLENGES

Recreating the abs() function in C++ with O(1) Time Complexity

Practice Read the full explanation

The absolute value function (abs() in many languages) returns the absolute value of a number. This means that it returns a number's positive value. You can think of it as the distance away from zero.

Create your own function that recreates this functionality, using the name and parameter n from the starter code.

Examples:

abs(-12) ➞ 12

abs(-544) ➞ 544

abs(250) ➞ 250

abs(0) ➞ 0

abs(-14) ➞ 14

Note:

Do not use the absolute value function provided by C++ (it will defeat the purpose of the challenge)


Hints:


You can make use of < operator with an if statement to check if n is negative.

You can add an else statement to handle the case when n is positive.
STEP 1 OF 3
    Ctrl + Enter to check

    C++ · CONDITIONAL STATEMENTS - CHALLENGES

    Recreating Abs in C++, explained

    Understanding the Problem

    The core challenge of this problem is to determine the absolute value of a given number without using the built-in abs() function. The absolute value of a number is its non-negative value, regardless of its sign. This function is commonly used in various mathematical computations and algorithms.

    Potential pitfalls include handling negative numbers correctly and ensuring that zero and positive numbers remain unchanged.

    Approach

    To solve this problem, we can use a simple conditional check:

    • If the number is negative, return its negation (which will be positive).
    • If the number is non-negative, return it as is.

    This approach ensures that we handle all possible inputs correctly.

    Naive Solution

    A naive solution would involve checking the sign of the number and returning the appropriate value. This solution is straightforward and has a time complexity of O(1), which is optimal for this problem.

    Optimized Solution

    Since the naive solution already provides an optimal time complexity of O(1), there is no need for further optimization. The key is to implement the solution correctly and efficiently.

    Algorithm

    Here is a step-by-step breakdown of the algorithm:

    1. Check if the number is less than zero.
    2. If it is, return the negation of the number.
    3. If it is not, return the number as is.

    Code Implementation

    
    #include <iostream>
    
    // Function to return the absolute value of a number
    double abs(double n) {
        // Check if the number is negative
        if (n < 0) {
            return -n; // Return the negation of the number
        } else {
            return n; // Return the number as is
        }
    }
    
    int main() {
        // Test cases
        std::cout << abs(-1.217197940) << std::endl; // ➞ 1.21719794
        std::cout << abs(-544.0) << std::endl; // ➞ 544
        std::cout << abs(250.3) << std::endl; // ➞ 250.3
        std::cout << abs(0) << std::endl; // ➞ 0
        std::cout << abs(-0.14) << std::endl; // ➞ 0.14
        return 0;
    }
    

    Complexity Analysis

    The time complexity of this solution is O(1) because it involves a single conditional check and a return statement. The space complexity is also O(1) as no additional space is required.

    Edge Cases

    Potential edge cases include:

    • Zero: The function should return zero.
    • Negative numbers: The function should return their positive counterparts.
    • Positive numbers: The function should return them unchanged.

    These edge cases are handled correctly by the provided implementation.

    Testing

    To test the solution comprehensively, consider the following test cases:

    • Negative floating-point numbers
    • Negative integers
    • Positive floating-point numbers
    • Positive integers
    • Zero

    Using a variety of test cases ensures that the function works correctly in all scenarios.

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Understand the problem requirements and constraints.
    • Break down the problem into smaller, manageable steps.
    • Consider edge cases and how to handle them.
    • Write clean, readable code with comments to explain your logic.

    Practicing similar problems and studying algorithms can help improve problem-solving skills.

    Conclusion

    In this blog post, we discussed how to recreate the abs() function in C++ without using the built-in function. We covered the problem definition, approach, algorithm, code implementation, complexity analysis, edge cases, and testing. Understanding and solving such problems is crucial for developing strong problem-solving skills.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with C++About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free