Fastest way to check if two integers are on the same side of 0

后端 未结 6 1527
后悔当初
后悔当初 2021-02-02 10:02

I need to check if two integers are on the same side of zero many times. I don\'t care if it\'s positive or negative, just that it\'s the same side... and performance is very im

6条回答
  •  不知归路
    2021-02-02 10:40

    Alternate answers

    Compare the sign bit

    return ((n >> 31) ^ (n2 >> 31) ) == 0 ? /* same */ : /* different */;
    

    Alternate way of comparing sign bit

    return (((int1 & 0x80000000) ^ (int2 & 0x80000000))) == 0 ? /* same */ : /* different */;
    

    and I just verified but Op's code is wrong when int1 == int2. The following will always print different if they are the same.

    if (int1 == 0 || int2 == 0) {
        // handle zero
    } else if ((int1 ^ int2) < 0) {
        // same side
    } else {
        // different side
    }
    

提交回复
热议问题