我必须使用位操作找到两个数字中的较大者。这些是相同的规则:
/*
* isGreater - if x > y then return 1, else return 0
* Example: isGreater(4,5) = 0, isGreater(5,4) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
*/
这是我为此编写的代码:
int isGreater(int x, int y) {
/* to find greater, subtract y from x using 2's complement method.
* then find 2's complement of the answer and shift right by 31 to give MSB
* which is 1 if x>y and 0 if x<y */
int ydash=(~y)+0x01;
int diff=x+ydash;
int a=(~diff)+0x01;
int b=a>>31;
int c=b&0x01;
return c;
}
为此我得到了这个错误:
ERROR: Test isGreater(-2147483648[0x80000000],2147483647[0x7fffffff]) failed... ...Gives 1[0x1]. Should be 0[0x0]
我可以使用 unsigned int,但不能使用其他数据类型。我不确定那会有什么帮助。我该如何解决这个问题?
最佳答案
此处可能不允许您使用 if-else 或任何控制语句。但是您可以“构造”一些类似 if-else 的语句。
int isGreater(int x, int y) {
int sgnext_x = x >> 31; //sgnext_x = x >= 0 ? 00000000 : 11111111
int sgnext_y = y >> 31;
int sgn_y = sgnext_y & 1; //sgn_y = y >= 0 ? 0 : 1
int minus = x + (~y + 1); // a - b = a + (~b+1)
int sgn_minus =(minus >> 31) & 1;
//A control-like statement. ((statement & a) | (!(statement | (b))))
//Returns a if statment = 11111111
//Returns (b&1) if statment = 00000000
int which = sgnext_x ^sgnext_y;
int result = (!!(x^y)) & ((which & sgn_y) | (!(which | (sgn_minus))));
return result;
}
关于c - 通过按位运算获取两个数中的较大者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28141981/