Simplest way to check if two integers have same sign?

前端 未结 18 2569
礼貌的吻别
礼貌的吻别 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

    I'm not really sure I'd consider "bitwise trick" and "simplest" to be synonymous. I see a lot of answers that are assuming signed 32-bit integers (though it would be silly to ask for unsigned); I'm not certain they'd apply to floating-point values.

    It seems like the "simplest" check would be to compare how both values compare to 0; this is pretty generic assuming the types can be compared:

    bool compare(T left, T right)
    {
        return (left < 0) == (right < 0);
    }
    

    If the signs are opposite, you get false. If the signs are the same, you get true.

提交回复
热议问题