Search code examples
c++cbinarylogicbit-manipulation

How to find TMax without using shifts


Using ONLY

 ! ~ & ^ | +

How can I find out if a 32 bit number is TMax?

TMax is the maximum, two's complement number.

My thoughts so far have been:

int isTMax(int x)
{
  int y = 0;
  x = ~x;
  y = x + x;
  return !y;
}

That is just one of the many things I have unsuccessfully have tried but I just cant think of a property of TMax that would give me TMax back. Like adding tmax to itself would be unique compared to all the other integers.


Here is the actual problem:

/*
 * isTMax - return 1 if x is the maximum, two's complement number,
 *     and 0 return otherwise. 
 *   Legal ops: ! ~ & ^ | +
 *   Max ops: 10
 *   Rating: 1
 */
int isTMax(int x) {
  int y = 0;
  x = ~x;
  y = x + x;

  return !y;
}

int is 32 bits so the max signed would probably be 0x7FFFFFFF


Solution

  • Something like this perhaps? 0x7FFFFFFF is the maximum positive signed 32 bit two's complement number.

    int isTMax(int x){
        return !(x ^ 0x7FFFFFFF);
    }
    

    I am not sure, you may need to cast it to unsigned for it to work.