//3 /* * 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 */ intisAsciiDigit(int x){ int min=0x2f+(~x+1); int max=0x39+(~x+1); min=!!(min>>31); max=!(max>>31); return min&max;//利用符号位判断,若在min=-1,max=0然后进行对min的二次取非得到1,max取非得到1,二者取&;大于9的min=-1,max=-1运算后得0,小于0的min=0,max=0运算还是0 }
7.conditional
解析见注释
1 2 3 4 5 6 7 8 9 10 11
/* * conditional - same as x ? y : z * Example: conditional(2,4,5) = 4 * Legal ops: ! ~ & ^ | + << >> * Max ops: 16 * Rating: 3 */ intconditional(int x, int y, int z){ x=~(!!x)+1; return (x&y)|(~x&z);//三目运算符构造,输入0取双非,得0,取反+1还是0,0&y得到0,~0&z得到z;输入非0,取双非得1,取反加一得-1,~-1&z=0,-1&y=y }
8.isLessOrEqual
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* * isLessOrEqual - if x <= y then return 1, else return 0 * Example: isLessOrEqual(4,5) = 1. * Legal ops: ! ~ & ^ | + << >> * Max ops: 24 * Rating: 3 */ intisLessOrEqual(int x, int y){ int a=x+(1+~y); int b=(a>>31); int c=(x>>31); int d=(y>>31); return (!!b & !(c ^ d)) /*x<y*/| ((c ^ 0x0) & !(d ^0x0)) | !(x^y)/*x=y*/ & !(!(y << 1) & (y ^0x0)); //判断x<=y true rt1 false rt2 依然利用符号位,但是需要考虑四种情况 x-y<0同号,x=y,x<0 y>0异号,x=最小值 }
9.logicalNeg
解析见注释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//4 /* * logicalNeg - implement the ! operator, using all of * the legal operators except ! * Examples: logicalNeg(3) = 0, logicalNeg(0) = 1 * Legal ops: ~ & ^ | + << >> * Max ops: 12 * Rating: 4 */ intlogicalNeg(int x){ x|=(x<<16); x|=x<<8; x|=x<<4; x|=x<<2; x|=x<<1; return((x>>31)+1);//构造非门,只要不是全0的0输入,有1就是1,取1的符号位+1