检查最简单的方法,如果两个整数具有相同的符号? [英] Simplest way to check if two integers have same sign?

查看:89
本文介绍了检查最简单的方法,如果两个整数具有相同的符号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是检查两个整数具有相同的符号最简单的方法?是否有任何短按位把戏做到这一点?

Which is the simplest way to check if two integers have same sign? Is there any short bitwise trick to do this?

推荐答案

下面的是,在C / C ++,不依赖于整数大小或有溢出的问题(工作即X * Y版本> = 0没有按' ŧ工作)

Here is a version that works in C/C++ that doesn't rely on integer sizes or have the overflow problem (i.e. x*y>=0 doesn't work)

bool SameSign(int x, int y)
{
    return (x >= 0) ^ (y < 0);
}

当然,你也可以怪胎出来,模板:

Of course, you can geek out and template:

template <typename valueType>
bool SameSign(typename valueType x, typename valueType y)
{
    return (x >= 0) ^ (y < 0);
}

注:由于我们使用的异或,我们希望LHS和RHS时的符号相同,从而免受零的不同的检查是不同的。

Note: Since we are using exclusive or, we want the LHS and the RHS to be different when the signs are the same, thus the different check against zero.

这篇关于检查最简单的方法,如果两个整数具有相同的符号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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