int logicalShift(int x, int n) { return 2; } /* * bang - Compute !x without usin
ID: 3593217 • Letter: I
Question
int logicalShift(int x, int n) {
return 2;
}
/*
* bang - Compute !x without using !
* Examples: bang(3) = 0, bang(0) = 1
* Legal ops: ~ & ^ | + << >>
* Max ops: 12
* Rating: 4
*/
int bang(int x) {
return 2;
}
/*
* tmin - return minimum two's complement integer
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 4
* Rating: 1
*/
int tmin(void) {
return 2;
}
/*
* fitsBits - return 1 if x can be represented as an
* n-bit, two's complement integer.
* 1 <= n <= 32
* Examples: fitsBits(5,3) = 0, fitsBits(-4,3) = 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 15
* Rating: 2
*/
Explanation / Answer
int bang(int x) {
/* Similar to bit parity, except use OR to accumlate any 1's in the number.*/
x = ( x >> 16 ) | x;
x = ( x >> 8 ) | x;
x = ( x >> 4 ) | x;
x = ( x >> 2 ) | x;
x = ( x >> 1) | x;
return ~x & 1;
}
int tmin(void)
{
/*shift the '1' bit to get 0x80000000*/
return 1 << 31;
}
int fitsBits(int x, int n) {
/* mask the sign bit against ~x and vice versa to get highest bit in x. Shift by n-1, and not. */
int mask = x >> 31;
return !(((~x & mask) + (x & ~mask)) >> (n + ~0));
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.