c - C在减法期间检查溢出
问题描述
我一直在尝试确定减去两个 32 位数字时是否存在溢出。我得到的规则是:
Can only use: ! ~ & ^ | + << >>
* Max uses: 20
Example: subCheck(0x80000000,0x80000000) = 1,
* subCheck(0x80000000,0x70000000) = 0
No conditionals, loops, additional functions, or casting
到目前为止我有
int dif = x - y; // dif is x - y
int sX = x >> 31; // get the sign of x
int sY = y >> 31; // get the sign of y
int sDif = dif >> 31; // get the sign of the difference
return (((!!sX) & (!!sY)) | (!sY)); // if the sign of x and the sign of y
// are the same, no overflow. If y is
// 0, no overflow.
我现在意识到我不能在实际函数中使用减法(-),所以我的整个函数无论如何都没用。如何使用与减法不同的方法并仅使用按位运算确定是否存在溢出?
解决方案
谢谢大家的帮助!这是我想出解决我的问题:
int ny = 1 + ~y; // -y
int dif = x + ny; // dif is x - y
int sX = x >> 31; // get the sign of x
int sY = y >> 31; // get the sign of -y
int sDif = dif >> 31; // get the sign of the difference
return (!(sX ^ sY) | !(sDif ^ sX));
我尝试过的每个案例都有效。我改变了@HackerBoss 的建议,通过获取 y 而不是 ny 的符号,然后在 return 语句中反转这两个检查。这样,如果符号相同,或者结果的符号和 x 的符号相同,则返回 true。
推荐阅读
- jquery - sweetalert2 在 Laravel 中调用 Confirm POST 提交按钮失败
- linux-device-driver - 我们有办法通过 nvmecli 读取 NVMe 驱动程序的完成队列条目吗?
- javascript - JavaScript 如何在不同文件夹中使用自己的 JavaScript 文件加载 HTMP 页面?不断收到错误 GET http://localhost:x/f.js 404 (Not Found) 为什么?
- prolog - Prolog 中按值结果传递如何工作的示例
- oracle - 我对 oracle sql developer 有一个问题,包括一个 with 函数不起作用
- java - 按名称比较两个对象列表并获取不同对象的列表
- google-app-engine - 在哪里以及如何应用用户权限并删除使任何用户都能够访问 GCP 的配置?
- angular - font-awesome 图标在 angular 10+ 中不起作用
- javascript - 使用 ReactMemo 渲染异步值
- python - Python:与非 Python 用户共享交互式绘图(离线)