/* * 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; x=~x+1; int result=(x&y)+(~x&z); return result; }
这题就是0+1和1+1的技巧,貌似也没啥。
8
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 sigh=0x1<<31; int bitXor=(!(x&sigh))^(!(y&sigh));
int m=~x+1+y; m=m>>31; return ((!bitXor)&(!m)|(bitXor&(x>>31))); }
略
9
1
/* * 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){ return ((x|(~x+1))>>31)+1;}
这里需要注意的是,补码右移的性质
负数在内存中表示的话最高位是符号位 负数为 1
做右移的话最高位会用1填充。
右移31位的话那么最后的数就是 0xffffffff了。 这个在内存中表示的就是有符号数的 -1
其次就是0的负数最高位仍然是0。
10
1
/* howManyBits - return the minimum number of bits required to represent x in * two's complement * Examples: howManyBits(12) = 5 * howManyBits(298) = 10 * howManyBits(-5) = 4 * howManyBits(0) = 1 * howManyBits(-1) = 1 * howManyBits(0x80000000) = 32 * Legal ops: ! ~ & ^ | + << >> * Max ops: 90 * Rating: 4 */inthowManyBits(int x){ int i16,i8,i4,i2,i1,i0; int sigh=x>>31; x=(sigh&~x)|(~sigh&x); i16=!!(x>>16)<<4; x=x>>i16; i8=!!(x>>8)<<3; x=x>>i8; i4=!!(x>>4)<<2; x=x>>i4; i2=!!(x>>2)<<1; x=x>>i2; i1=!!(x>>1); x=x>>i1; i0=x; return i16+i8+i4+i2+i1+i0+1;}
就是让你判断x用补码表示最少需要几位
就是一个二分的思想。
11
1
/* * floatScale2 - Return bit-level equivalent of expression 2*f for * floating point argument f. * Both the argument and result are passed as unsigned int's, but * they are to be interpreted as the bit-level representation of * single-precision floating point values. * When argument is NaN, return argument * Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while * Max ops: 30 * Rating: 4 */unsignedfloatScale2(unsigned uf){ intexp=(uf&0x7f800000)>>23; int sigh=uf&(1<<31); if(exp==0) return uf<<1|sigh; if(exp==255) return uf; exp+=1; if(exp==255) return0x7f800000|sigh; return (exp<<23)|(uf&0x807fffff);}
/* * floatFloat2Int - Return bit-level equivalent of expression (int) f * for floating point argument f. * Argument is passed as unsigned int, but * it is to be interpreted as the bit-level representation of a * single-precision floating point value. * Anything out of range (including NaN and infinity) should return * 0x80000000u. * Legal ops: Any integer/unsigned operations incl. ||, &&. also if, while * Max ops: 30 * Rating: 4 */intfloatFloat2Int(unsigned uf){ int sigh=uf>>31; intexp=((uf&0x7f800000)>>23)-127; int result=(uf&0x007fffff)|0x00800000; if(!(uf&0x7fffffff)) return0; if(exp> 31) return0x80000000; if(exp<0) return0;}