比较两个整数没有任何比较

Ame*_*aki 11 c++ comparison if-statement

是否有可能在没有任何比较的情况下找到最大的两个整数?我找到了一些解决方案

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";
Run Code Online (Sandbox Code Playgroud)

但如果(c)或if(!c)是零的比较.此外,它不适用于负数.实际上我需要一个避免任何if语句的解决方案.相反,我应该使用switch语句和算术运算符.感谢名单.

Mar*_*ett 37

减去它们,并使用令人讨厌的位错误的方法检查标志
http://graphics.stanford.edu/~seander/bithacks.html

如果其他程序员知道您居住的地方,请不要在生产代码中执行此操作.

  • 同意最后一句。如果这对你的平台来说是个好主意,编译器应该为你做这个优化:) (2认同)

Ecl*_*pse 5

这是一个有趣的比特版本,没有任何条件分支.

int g = (int)"greater";
int l = (int)"less";
int e = (int)"equal";

int a = 7;
int b = 10;

char *result = (char*)((((a - b) >> 31) & l) | (((b - a) >> 31) & g) | ((~((a - b) | (b - a))) >> 31) & e);
cout << result;
Run Code Online (Sandbox Code Playgroud)