Check if a number x is positive (x>0) by ONLY using bitwise operators in C

后端 未结 12 601
夕颜
夕颜 2020-12-14 10:24

isPositive - return true if x > 0, otherwise false

Example: isPositive(-1)

Legal ops:

12条回答
  •  执笔经年
    2020-12-14 10:41

    Let's play with the sign bit: sign(~n) : 1 if n >= 0

    To get rid of the case when n is 0: sign(~n + 1) : 1 if n > 0 or n = MIN_INT

    So, we want the case when both functions return 1:

    return ((~n & (~n + 1)) >> 31) & 1;
    

提交回复
热议问题