16.07. Maximum
Description
Write a method that finds the maximum of two numbers. You should not use if-else or any other comparison operator.
Example:
Input: a = 1, b = 2 Output: 2
Solutions
Solution 1: Bitwise Operation
We can extract the sign bit \(k\) of \(a-b\). If the sign bit is \(1\), it means \(a \lt b\); if the sign bit is \(0\), it means \(a \ge b\).
Then the final result is \(a \times (k \oplus 1) + b \times k\).
The time complexity is \(O(1)\), and the space complexity is \(O(1)\).
1 2 3 4 |
|
1 2 3 4 5 6 |
|
1 2 3 4 5 6 7 |
|
1 2 3 4 |
|
1 2 3 4 |
|
1 2 3 4 5 6 7 |
|