Question: int fitsBits(int x, int n) { This algorithm attempts to slide the number to the left and back * to the right based on the

int fitsBits(int x, int n) {

"This algorithm attempts to "slide" the number to the left and back * to the right based on the number of bits entered by the user. * If a number can fit in an n-bit number, we should be able to move * it 32-n times to the left and back to the right without changing * the value of the number. If we move back to the right and pieces * of the number are missing, or we've accidentally "dragged" * the sign over to the right when it wasn't there before, * then it can't fit. * * The right shift behaves differently than I intended it to, but * it makes the program work, so it's staying!"

I've tried...

int mask = x >> 31;

return !(((~x & mask) + (x & ~mask)) >> (n + ~0));

And...

int shift = 32 + (~n + 1); // equal to 32 - n

return !(((x << shift) >> shift) ^ x);

None of my attempts are working, can someone help?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!