Simplest way to check if two integers have same sign?

前端 未结 18 2548
礼貌的吻别
礼貌的吻别 2020-12-04 13:53

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

18条回答
  •  無奈伤痛
    2020-12-04 14:41

    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 
    bool SameSign(typename valueType x, typename valueType y)
    {
        return (x >= 0) ^ (y < 0);
    }
    

    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.

提交回复
热议问题