Bitwise Less than or Equal to

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

    Really enjoyed Yanagar1's answer, which is very easy to understand.

    Actually we can remove those shift operators and use De Morgan's laws, which reduce the number of operators from 15 to 11.

    long isLessOrEqual(long x, long y) {
      long sign = (x ^ y);               // highest bit will be 1 if different sign
      long diff = sign & x;              // highest bit will be 1 if diff sign and neg x
      long same = sign | (y + (~x + 1)); // De Morgan's Law with the following ~same
                                         // highest bit will be 0 if same sign and y >= x
      long result = !!((diff | ~same) & 0x8000000000000000L); // take highest bit(sign) here
      return result;
    }
    

提交回复
热议问题