如何通过一次比较来检查一个数字是否在[low,high]范围内?

这是一个简单但有趣的编程难题。给定三个整数,low,high和x,使得high>=low。如何使用单一比较检查x是否位于范围[低、高]内。例如,如果范围为[10100],数字为30,则输出为真,如果数字为5,则相同范围的输出为假。 一个简单的解决方案是将x与低和高进行比较

null

C++

#include <iostream>
using namespace std;
// Returns true if x is in range [low..high], else false
bool inRange(unsigned low, unsigned high, unsigned x)
{
return (low <= x && x <= high);
}
int main()
{
inRange(10, 100, 30)? cout << "Yes" : cout << "No" ;
inRange(10, 100, 5)?  cout << "Yes" : cout << "No" ;
}


输出:

Yes
No

  The above solution does two comparisons, 
  Can we do the same task using one comparison?  

我们强烈建议您尽量减少浏览器,并先自己尝试。 这个想法是比较“x-low”和“high-x”。当且仅当x大于或等于低且小于或等于高时,x在范围[low,high]内。

CPP

#include <iostream>
using namespace std;
// Returns true if x is in range [low..high], else false
bool inRange(unsigned low, unsigned high, unsigned x)
{
return ((x-low) <= (high-low));
}
int main()
{
inRange(10, 100, 30)? cout << "Yes" :  cout  << "No" ;
inRange(10, 100, 5)?  cout << "Yes" :  cout  << "No" ;
}


输出:

Yes
No

对于[10100]和x=5,这是如何工作的? 当我们从5中减去10,我们得到-5,它被认为是无符号整数形式的单位_MAX-4。UNIT_MAX是可能的最大无符号整数值。这里的假设是,数字以2的补码形式存储。在2的补码形式中,-1代表UINT_MAX,-2代表UINT_MAX-1,。。等 感谢Utkarsh提出这个解决方案。 一个适用于负数的解决方案 这个想法是乘(x-低)和(x-高)。如果x在范围内,则它必须大于或等于low,即(x-low)>=0。并且必须小于或等于high,即(high–x)<=0。所以,若乘法的结果小于或等于0,那个么x在范围内。否则就不行了。感谢eva提出了这种方法。

CPP

#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, 30)? cout << "Yes" :  cout  << "No" ;
inRange(10, 100, 5)?  cout << "Yes" :  cout  << "No" ;
}


输出:

Yes
No

如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享