如何处理 fitBits 中的 n=32
从计算机系统:程序员的角度进行练习,这就是我想到的。不幸的是,这在 n=32 的情况下不起作用,如果 n=32 它根本不会移动 x,所以无论如何它都会返回 1。如果 x=0x80000000 这是一个问题,因为在这种情况下它应该返回 0
/*
* fitsBits - return 1 if x can be represented as an
* n-bit, two's complement integer.
* 1 <= n <= 32
* Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int fitsBits(int x, int n) {
int diff = 32 +(~n + 1);//diff between n and 32
return !(x ^ ((x << diff) >> diff)); //shifts x left by diff then right by diff leaving the num unchanged if it would fit as an n-bit 2s comp int then xor's with x so it will be !0 if x matches shifted x or !1 otherwise
}
working on an exercise from Computer Systems: A programmer's perspective and this is what i came up with. Unfortunatly this doesn't work in the case that n=32, if n=32 it doesn't shift x at all so it returns 1 regardless. This is a problem if x=0x80000000 because in this case it should return 0
/*
* fitsBits - return 1 if x can be represented as an
* n-bit, two's complement integer.
* 1 <= n <= 32
* Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
int fitsBits(int x, int n) {
int diff = 32 +(~n + 1);//diff between n and 32
return !(x ^ ((x << diff) >> diff)); //shifts x left by diff then right by diff leaving the num unchanged if it would fit as an n-bit 2s comp int then xor's with x so it will be !0 if x matches shifted x or !1 otherwise
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论