检查一个数字x为正数(X 0)通过用C仅用位运算符 [英] Check if a number x is positive (x>0) by ONLY using bitwise operators in C

查看:109
本文介绍了检查一个数字x为正数(X 0)通过用C仅用位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

isPositive - 符真正如果 X> 0 ,否则

例如: isPositive(-1)

法律OPS:<!code> &安培; ^ | + &LT;&LT ; &GT;&GT;

最大OPS: 8

注:没有条件语句允许

 内联BOOL isPositive(int32_t X){
  返回???;
}


解决方案

 返回((X安培;为0x80000000)GT;&GT;!31 | X)!;

isPositive - return true if x > 0, otherwise false

Example: isPositive(-1)

Legal ops: ! ~ & ^ | + << >>

Max ops: 8

Note: No conditional statements are allowed.

inline bool isPositive(int32_t x) {
  return ???;
}

解决方案

return !((x & 0x80000000) >> 31 | !x);

这篇关于检查一个数字x为正数(X 0)通过用C仅用位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆