Question
/* * isNonZero - Check whether x is nonzero using * the legal operators except ! * Examples: isNonZero(3) = 1, isNonZero(0) = 0 *
/* * isNonZero - Check whether x is nonzero using * the legal operators except ! * Examples: isNonZero(3) = 1, isNonZero(0) = 0 * Legal ops: ~ & ^ | + << >> * Max ops: 10 * Rating: 4 */ int isNonZero(int x) { return ((x | (~x + 1)) >> 31) & 1; } /* * leftBitCount - returns count of number of consective 1's in * left-hand (most significant) end of word. * Examples: leftBitCount(-1) = 32, leftBitCount(0xFFF0F0F0) = 12 * Legal ops: ! ~ & ^ | + << >> * Max ops: 50 * Rating: 4 */ int leftBitCount(int x) { int y, z, maskz; x = ~x; y = 0; maskz = 0xFF + (0xFF << 8); z = (x >> 16) & (maskz); y += (!z) << 4; x = x >> ((!!z) << 4);
z = (x >> 8) & (0xFF); y += (!z) << 3; x = x >> ((!!z) << 3);
z = (x >> 4) & (0xF); y += (!z) << 2; x = x >> ((!!z) << 2);
z = (x >> 2) & (0x3); y += (!z) << 1; x = x >> ((!!z) << 1);
z = (x >> 1) & (0x1); y += (!z); x = x >> (!!z);
z = (x) & (0x1); y += (!z);
return y; } /* * trueThreeFourths - multiplies by 3/4 rounding toward 0, * avoiding errors due to overflow * Examples: trueThreeFourths(11) = 8 * trueThreeFourths(-9) = -6 * trueThreeFourths(1073741824) = 805306368 (no overflow) * Legal ops: ! ~ & ^ | + << >> * Max ops: 20 * Rating: 4 */ int trueThreeFourths(int x) { int sign = x >> 31; int remain = x & 3;
x = x >> 2; x = x + (x << 1); x = x + ((remain + (remain << 1) + (sign & 3)) >> 2); return x; }
explain what each code does, I have a general understanding but want to know more of how each works
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started