Hey, I'm doing a homework problems and am very stuck.
This is your basic bitwise operator problem.
I have this one working for small values, but when they approach the maximum 2's compliment size, they return the wrong value.
Code:
/*
* 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
*/
int fitsBits(int x, int n)
{
int shift = 1 << n;
int test = (shift ^ (x << 1)) >> n;
return !!test;
}
If anyone's a guru at these problems, could you give me a hand. Thare are other's that I'm working on also, but I am very lost.