比较两个整数而不进行任何比较 [英] Comparing two integers without any comparison
问题描述
有没有可能找到最大的两个整数,没有任何比较?我发现了一些解决方案:
Is it possible to find the greatest of two integers without any comparison? I found some solutions:
if(!(a/b)) // if a is less than b then division result will be zero.
{
cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now. check whether they are equal.
{
cout << "a and b are equal";
}
else
cout << "a is greater than b";
但是如果(c)或if(!c)此外,它不适用于负数。事实上,我需要一个避免任何if语句的解决方案。相反,我应该使用switch语句和算术运算符。 ThanX。
But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.
推荐答案
减去它们并使用讨厌的比特twiddling工具检查符号
http://graphics.stanford.edu/~seander/bithacks.html
Subtract them and check the sign using nasty bit twiddling hacks
http://graphics.stanford.edu/~seander/bithacks.html
如果其他程序员知道你住在哪里,不要在生产代码中这样做。
Don't do this in production code if the other programmers know where you live.
这篇关于比较两个整数而不进行任何比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!