Number Max

16.7 Number Max: Write a method that finds the maximum of two numbers. You should not use if-else or any other comparison operator.

  • The idea is as follows:

    • c is the difference of a and b. If c is negative, then b must be larger.

    • To indicate for ourselves whether this is true, we do c >> 31 & 1, which if the number is negative, then 1 would be stored at the MSB or 32 second bit, decoded standard by 2's complement representation, by anding it with 1, we ignore all higher bits to get this 2's complement bit.

    • Now we preform a - c *k. If c == 1, then return b. Which will hold since c = a - b, and a - (a - b) = b. And when c == 0, return a: a - (0)

int max(int a, int b) {
  int c = a - b;
  int k = c >> 31 & 1;
  return a - (c * k);
}

Last updated