Find the maximum of two numbers. You should not use if-else or any other comparison operator. I found this question on online bulletin board, so i thought i should ask in StackOverflow
EXAMPLE Input: 5, 10 Output: 10
I found this solution, can someone help me understand these lines of code
int getMax(int a, int b) {
int c = a - b;
int k = (c >> 31) & 0x1;
int max = a - k * c;
return max;
}
Use bitwise hacks
If you know that
INT_MIN <= x - y <= INT_MAX,
then you can use the following, which is faster because(x - y)
only needs to be evaluated once.Source : Bit Twiddling Hacks by Sean Eron Anderson
Using the shifting idea to extract the sign as posted by others, here's another way:
This pushes the two numbers into an array with the maximum number given by the array-element whose index is sign bit of the difference between the two numbers.
Do note that:
(a - b
) may overflow.>>
operator refers to a logical right-shift, the& 1
is unnecessary.Here's how I think I'd do the job. It's not as readable as you might like, but when you start with "how do I do X without using the obvious way of doing X, you have to kind of expect that. In theory, this gives up some portability too, but you'd have to find a pretty unusual system to see a problem.
This does have some advantages over the one shown in the question. First of all, it calculates the correct size of shift, instead of being hard-coded for 32-bit ints. Second, with most compilers we can expect all the multiplication to happen at compile time, so all that's left at run time is trivial bit manipulation (subtract and shift) followed by a load and return. In short, this is almost certain to be pretty fast, even on the smallest microcontroller, where the original used multiplication that had to happen at run-time, so while it's probably pretty fast on a desktop machine, it'll often be quite a bit slower on a small microcontroller.
Here are a couple of bit-twiddling methods to get the max of two integral values:
Method 1
Explanation:
a > b
thena - b
is positive, thus the sign bit is0
, and the mask is0x00.00
. Otherwise,a < b
soa - b
is negative, the sign bit is1
and after shifting, we get a mask of0xFF..FF
0xFF..FF
, then~mask
is0x00..00
and then this value is0
. Otherwise,~mask
is0xFF..FF
and the value isa
0xFF..FF
, then this value isb
. Otherwise,mask
is0x00..00
and the value is0
.Finally:
a >= b
thena - b
is positive, we getmax = a | 0 = a
a < b
thena - b
is negative, we getmax = 0 | b = b
Method 2
Explanation:
a > b
the mask is0x00..00
, otherwise the mask is0xFF..FF
0x00..00
, then(a ^ b) & mask
is0x00..00
0xFF..FF
, then(a ^ b) & mask
isa ^ b
Finally:
a >= b
, we geta ^ 0x00..00 = a
a < b
, we geta ^ a ^ b = b
//In C# you can use math library to perform min or max function
using System;
class NumberComparator {
}