Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

int fitsBits(int x, int n) { \"This algorithm attempts to \"slide\" the number t

ID: 3664349 • Letter: I

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 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?

Explanation / Answer

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! */ int num; int equal; num = x; num = num > (32+(~n+1)); equal = x ^ num; equal = equal + 1; equal = equal >> 1; return !(equal); }