Is Number Negative? (Time Complexity: O(1), Language: C++)

Understanding the Problem

The core challenge of this problem is to determine whether a given number is negative or not. This is a fundamental problem in programming that helps in understanding conditional statements and basic comparison operations.

Significance and common applications include error checking, input validation, and decision-making processes in various algorithms.

Potential pitfalls include misunderstanding the comparison operators or not handling the zero case correctly.

Approach

To solve this problem, we can use a simple conditional statement to check if the number is less than zero. If it is, we print "negative"; otherwise, we print "positive". This approach is straightforward and efficient.

Initial naive solution: Directly use an if-else statement to check the condition. This is optimal for this problem as it has a constant time complexity of O(1).

Algorithm

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

  1. Take the input number n.
  2. Check if n is less than zero using the < operator.
  3. If the condition is true, print "negative".
  4. Otherwise, print "positive".

Code Implementation

#include <iostream>  // Include the iostream library for input and output

// Function to check if a number is negative or positive
void checkNumber(int n) {
    // If the number is less than zero, print "negative"
    if (n < 0) {
        std::cout << "negative" << std::endl;
    } 
    // Otherwise, print "positive"
    else {
        std::cout << "positive" << std::endl;
    }
}

// Main function
int main() {
    // Test cases
    checkNumber(5);  // Output: positive
    checkNumber(0);  // Output: positive
    checkNumber(-2); // Output: negative

    return 0;
}

Complexity Analysis

The time complexity of this approach is O(1) because the comparison and print operations take constant time. The space complexity is also O(1) as no additional space is required.

Edge Cases

Potential edge cases include:

Examples:

checkNumber(0);  // Output: positive
checkNumber(-1000000);  // Output: negative
checkNumber(1000000);  // Output: positive

Testing

To test the solution comprehensively, consider a variety of test cases:

Testing frameworks like Google Test can be used for automated testing.

Thinking and Problem-Solving Tips

When approaching such problems:

Conclusion

In this blog post, we discussed how to determine if a number is negative or positive using a simple conditional statement in C++. 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 programming skills.

Additional Resources

For further reading and practice problems, consider the following resources: