| comments | true |
|---|---|
| difficulty | Easy |
| edit_url | https://github.com/doocs/leetcode/edit/main/lcci/16.07.Maximum/README_EN.md |
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
We can extract the sign bit
Then the final result is
The time complexity is
class Solution:
def maximum(self, a: int, b: int) -> int:
k = (int(((a - b) & 0xFFFFFFFFFFFFFFFF) >> 63)) & 1
return a * (k ^ 1) + b * kclass Solution {
public int maximum(int a, int b) {
int k = (int) (((long) a - (long) b) >> 63) & 1;
return a * (k ^ 1) + b * k;
}
}class Solution {
public:
int maximum(int a, int b) {
int k = ((static_cast<long long>(a) - static_cast<long long>(b)) >> 63) & 1;
return a * (k ^ 1) + b * k;
}
};func maximum(a int, b int) int {
k := (a - b) >> 63 & 1
return a*(k^1) + b*k
}function maximum(a: number, b: number): number {
const k: number = Number(((BigInt(a) - BigInt(b)) >> BigInt(63)) & BigInt(1));
return a * (k ^ 1) + b * k;
}class Solution {
func maximum(_ a: Int, _ b: Int) -> Int {
let diff = Int64(a) - Int64(b)
let k = Int((diff >> 63) & 1)
return a * (k ^ 1) + b * k
}
}