比较两个整数而不进行任何比较 [英] Comparing two integers without any comparison

查看:154
本文介绍了比较两个整数而不进行任何比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能找到最大的两个整数,没有任何比较?我找到了一些解决方案:

  if(!(a / b))//如果a小于b,为零。 
{
cout<< b大于a;
}
else if(!(a-b))//我们知道a大于或等于b现在。检查它们是否相等。
{
cout<< a和b相等;
}
else
cout<< a大于b;

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


解决方案

使用讨厌的bit twiddling工具来减去它们并检查符号

http://graphics.stanford.edu/~seander/bithacks.html



如果其他程序员知道你住在哪里,不要在生产代码中这样做。


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";

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.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆