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

后端 未结 6 1530
后悔当初
后悔当初 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:29

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

    or

    if (int1 == 0 || int2 == 0) {
        // handle zero
    } else if ((int1 & Integer.MIN_VALUE) == (int2 & Integer.MIN_VALUE)) {
        // same side
    } else {
        // different side
    }
    

    The idea of both is the same - strip all but the sign bit, and then compare that for equality. I'm not sure which is faster, the right shift (>>) or the bitwise and (&).

提交回复
热议问题