我必须重新编写一个方法,仅使用按位运算符和没有条件语句来查明x是否小于或等于y。到目前为止我有这个:
int isLessOrEqual(int x, int y)
{
int a = x + (~y) + 1;
return ((a&0x80000000) >> 31);
}
但我不知道如何防范溢出?任何人都可以伸出援助之手吗?
答案 0 :(得分:0)
[编辑]错误的解决方案,因为它使用条件。我会暂时搁置它,因为它可能会提供见解。
假设我们知道int
是4字节2的恭维。
if (x == y) return 1;
int SignMask = 0x80000000;
// if x & y have different signs ...
if ((x & SignMask) != (y & SignMask)) {
return !!(x & SignMask);
}
// Continue with your original code knowing overflow will not happen.
答案 1 :(得分:0)
仅仅为了练习,下面的扭曲代码将没有任何“+”或条件语句(除非你考虑转换为布尔条件)。
#define MSB 0x80000000
typedef bool (*RecurseFunc)(unsigned int, unsigned int);
bool EndRecursion(unsigned int ux, unsigned int uy)
{
// stop recursion - ux cannot be smaller than uy
return false;
}
bool CompareMSB(unsigned int ux, unsigned int uy)
{
// jump table, may make global...
RecurseFunc Handler[2] = {EndRecursion, CompareMSB};
// yMsbBigger == MSB only iff Y"MSB==1 and X:MSB==0
unsigned int yMsbBigger = ((~ux) & uy) & MSB;
// differentMsb will be MSB only iff the MSB of Y different MSB of x
unsigned int differentMsb = (uy ^ ux) & MSB;
// prepare to check on the next bit - shift it to MSB position
ux <<= 1;
uy <<= 1;
// we may want to check the remaining bits if ux,uy had same signs and
// the remaining bits of y are not all 0
bool mayRecurse = ((bool)uy) && (!(bool)differentMsb);
// C will not evaluate the second expression if the first is true
// the second expression will "EndRecursion" if we may not recurse -
// otherwise recurse
return (((bool)yMsbBigger) || Handler[mayRecurse](ux, uy));
}
bool isYGreater(int x, int y)
{
// we reverse the sign bits so positive value will have MSB=1, making it
// "greater" then negative value's MSB
unsigned int xbits = (unsigned int)x ^ MSB;
unsigned int ybits = (unsigned int)y ^ MSB;
return (CompareMSB(xbits, ybits));
}