Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to check whether a number is in range[low,high] using one comparison?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 131
    Comment on it
    #include <iostream>
    using namespace std;
    
    // Returns true if x is in range [low..high], else false
    bool inRange(int low, int high, int x)
    {
        return ((x-high)*(x-low) <= 0);
    }
    
    int main()
    {
        inRange(10, 100, 25)? cout << "Yes\n":  cout  <<"No\n";
        inRange(10, 100, 6)?  cout << "Yes\n":  cout  <<"No\n";
    }

    Output:

    Yes

    No

    Explanation:

    The concept used in above program is subtracting low from x and subtracting high from x and multiplying them. If x is in the range[low,high] then x is greater then or equal to low therefore result of the expression (x-low) is greater then equal to 0, in case of high for x to be in range[low,high], x must be less then or equal to high thus result of the expression (x-high) returns a negative number or 0 thus multiplying these two expression if multiplied result is less then or equal to 0 then a true is returned else false.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: