Max with no Comparitor

/**
* Write a function that finds the maximum of two numbers.
*
* You should not use if-else or any other comparison operator.
*/

/*
The idea:
- First to understand the solution, we have to know a few things.
- 2's complement. The final bit of any number by the IEEE standard
  makes sure that if a number is negative, then the final bit is 1.
  Otherwise, it is get to zero. We can observe this:

int test = INT_MAX;
bitset<32> x(test);
cout << x << endl;

int test1 = -INT_MAX;
bitset<32> x2(test1);
cout << x2 << endl;

- So to receive the maximum number, we can observe whether or not
  the difference between two numbers is negative. If it is, depending
  on the order we presented it in. One of those numbers are negative.
- To get the 32nd bit we shift 1 to the right 31 times and AND it with 
  1, which has the effect of copying the bit by boolean logic.
- Then, if we have two cases:
    - Multipling it by 0 + first = first;
    - Multipling it by 1 + first = (difference) + first = second, since 
      difference will always be negative and it has the effect of subtracting
      from the first number, returning the second number.

*/

int max_no_comp(int first, int second)
{
    int diff = first - second;
    return (diff * (diff & 1 << 31)) + first;
}

int main()
{
    cout << max_no_comp(40, 20) << endl;
    cout << max_no_comp(20, 40) << endl;
    cout << max_no_comp(-232, 23232) << endl;
    cout << max_no_comp(23232,-232) << endl;
}

Last updated