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

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

问题描述

检查两个整数是否具有相同符号的最简单方法是什么?有什么简单的按位技巧吗?

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);
}

当然,你可以geek out和template:

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天全站免登陆