5.negate
/* negate - return -x
* Example: negate(1) = -1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 5
* Rating: 2
*/
int negate(int x) {
return ~x + 1;
}
6.isAsciiDigit
/*
* isAsciiDigit - return 1 if 0x30 <= x <= 0x39 (ASCII codes for characters '0' to '9')
* Example: isAsciiDigit(0x35) = 1.
* isAsciiDigit(0x3a) = 0.
* isAsciiDigit(0x05) = 0.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 3
*/
int isAsciiDigit(int x) {
return !((x + ~0x30)>>31) | ((0x39 + ~x)>>31));
}
思路:
x-0x30>=0------>(x+~0x30)=a
0x39-x>=0------>(0x39+~x)=b
此时我们只需要判断符号位了,当a,b均大于等于0时,a和b的符号位肯定为0。所以我们分别将a,b右移31位,当a,b均为0时,判断为真。
7. conditional
/*
* conditional - same as x ? y : z
* Example: conditional(2,4,5) = 4
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 16
* Rating: 3
*/
int conditional(int x, int y, int z) {
int mask = ((!! x)<<31)>>31
return (~mask & z) | (mask & y);
}
思路:
a = !! x
b = ((x<<31)>>31)
1. x = 0, b = 0;
2. x != 0, b = 1111111111;
“掩码”