I was intrigued by the following question -
Find the maximum of two numbers without using any if-else statements, branching, or direct comparisons.
Understanding the problem
The problem seems straight forward - do not use code that would compare the numbers directly, and no code that makes choices
Brain Storming
I came up with a few options and did rightly suspect that the solution existed in
- A mathematical equation, or
- An equation that involved the shift operator
I was not familiar with the mathematical formula, nor was I familiar with using the shift operator.
I decided to solve this with the last option I came up with -
The "wrong" way ?
The solution I chose involved -
- Decreasing both numbers until one reached zero.
- Keep track of how many times we decreased the number in a count variable
- When one value reached zero we could add all 3 values, to arrive at the max value
This of course is highly inefficient and would only work with positive numbers
The following website has a really good explanation on how to solve this problem mathematically -
https://www.geeksforgeeks.org/compute-the-minimum-or-maximum-max-of-two-integers-without-branching/