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

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

    (int1 ^ int2) >> 31 == 0 ? /*on same side*/ : /*different side*/ ; This doesn't necessarily handle 0 correctly I'm not sure what you wanted to do in that case.
    EDIT: also wanted to point out that if this was in c instead of java, it could be optimized further by getting rid of the == 0 because of the way that booleans work in c, the cases would be switched though

提交回复
热议问题