Bitwise Less than or Equal to

前端 未结 5 1871
-上瘾入骨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:29

    Here is my implementation(spend around 3 hours...)

    int
    isLessOrEqual(int x, int y)
    {
        int a = y + ~x + 1;
        int b = a & 1 << 31 & a; // !b => y >= x, but maybe overflow
        int c = !!(x & (1 << 31)) & !(y & (1 << 31)); // y > 0, x < 0
        int d = !(x & (1 << 31)) & !!(y & (1 << 31)); // x > 0, y < 0
    
        int mask1 = !c + ~0;
    
        // if y > 0 && x < 0, return 1. else return !b
        int ans = ~mask1 & !b | mask1 & 1;
    
        int mask2 = !d + ~0;
    
      // if y < 0 && x > 0, return 0, else return ans
        return ~mask2 & ans | mask2 & 0;
    }
    
    • y - x == y + ~x + 1

    • a & 1 << 31 & a is simplify from !(!(a & (1 << 31)) | !a)

    The logic is:

    if `y > 0 && x < 0`
        return true  
    if `x > 0 && y < 0`
        return false
    
    return y >= x
    

    Why not just y >= x directly? because overflow may happen. So I have to early return to avoid overflow.

提交回复
热议问题