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

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

    0 讨论(0)
  • 2021-02-02 10:28

    I would bitcast them to unsigned int, and xor the MSB (most-significant-bit) - much faster than any comparison (which does a subtraction) or multiplication

    0 讨论(0)
  • 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 (&).

    0 讨论(0)
  • 2021-02-02 10:32
     int int1    = 3;
     int int2    = 4;
     boolean res = ( (int1 * int2) >= 0) ? true : false;
    
     System.out.println(res);
    
    0 讨论(0)
  • 2021-02-02 10:39

    Another answer...

    final int i = int1 ^ int2;
    
    if (i == 0 && int1 == 0) {
        // both are zero
    } else if (i & Integer.MIN_VALUE == Integer.MIN_VALUE) {
        // signs differ
    } else {
        // same sign
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题