How to check whether a number is in the range[low, high] using one comparison ? - GeeksforGeeks
Given three positive integers, low, high and x such that high >= low. How to check if x lies in range [low, high] or not. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output is false for same range.
Read full article from How to check whether a number is in the range[low, high] using one comparison ? - GeeksforGeeks
Given three positive integers, low, high and x such that high >= low. How to check if x lies in range [low, high] or not. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output is false for same range.
bool
inRange(unsigned low, unsigned high, unsigned x)
{
return
((x-low) <= (high-low));
}
When we subtract 10 from 5, we get -5 which is considered as UNIT_MAX-4 in unsigned int form. UNIT_MAX is maximum possible unsigned int value. The assumption here is, numbers are stored in 2’s complement form. In 2’s complement form, -1 represents UINT_MAX, -2 represets UINT_MAX-1,..etc.
bool
inRange(unsigned low, unsigned high, unsigned x)
{
return
(low <= x && x <= high);
}