Bitwise Less than or Equal to

前端 未结 5 1870
-上瘾入骨i
-上瘾入骨i 2021-01-19 02:49

There seems to be some kind of misconception that this is for a contest. I\'m trying to work through an assignment and I\'ve been stuck on this for an hour now.

<         


        
5条回答
  •  臣服心动
    2021-01-19 03:41

    Inspired by Yanagar1's answer, here's my implementation:

    int isLessOrEqual(int x, int y) {
    
        int indicator = !((y + (~x + 1)) >> 31); // negation of the result of y - x, 0 when y < x, -1 when y >= x
        int xsign = x >> 31; // -1 when x < 0, 0 when x >= 0
        int ysign = y >> 31; // -1 when y < 0, 0 when y >= 0
        int xbool = !xsign; // 0 when x < 0, 1 when x >= 0
        int ybool = !ysign; // 0 when y < 0, 1 when y >= 0
        int result = (!(xbool ^ ybool)) & indicator;
        return result | (ybool & !xbool);
    }
    

    Explanation: Adding 2's complement negation of x (~x + 1) to y is essentially calculating y - x, then logical negate the sign bit of the result, we can have 0 when y < x, and 1 when y >= x. But there are potential overflow cases (overflow cannot happen when y and -x have opposite signs, that is, when y and x have same signs):

    |-----------|------------------------|------------------------|
    |           |         y > 0          |         y < 0          |
    |-----------|------------------------|------------------------|
    |   x > 0   |           ok           | overflow when y = TMin |
    |-----------|------------------------|------------------------|
    |   x < 0   | overflow when x = TMin |           ok           |
    |-----------|------------------------|------------------------|
    

    so we need to be careful when the signs are different.

提交回复
热议问题