Method 2(Use subtraction and shift)
public static int min(int x, int y) {
int diff = (x - y);
return y + (diff & diff >> 31);
}
public static int max(int x, int y) {
int diff = (x - y);
return x - (diff & diff >> 31);
}
Read full article from Compute the minimum or maximum of two integers without branching | GeeksforGeeks
Minimum of x and y will be
y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))
This method shifts the subtraction of x and y by 31 (if size of integer is 32). If (x-y) is smaller than 0, then (x -y)>>31 will be -1. If (x-y) is greater than or equal to 0, then (x -y)>>31 will be 0.
So if x >= y, we get minimum as y + (x-y)&0 which is y.
If x < y, we get minimum as y + (x-y)&1 which is x.
So if x >= y, we get minimum as y + (x-y)&0 which is y.
If x < y, we get minimum as y + (x-y)&1 which is x.
Similarly, to find the maximum use
x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)))
Java Version: This will not work if the minus operation overflows.int
min(
int
x,
int
y)
{
return
y + ((x - y) & ((x - y) >>
(
sizeof
(
int
) * CHAR_BIT - 1)));
}
/*Function to find maximum of x and y*/
int
max(
int
x,
int
y)
{
return
x - ((x - y) & ((x - y) >>
(
sizeof
(
int
) * CHAR_BIT - 1)));
}
public static int min(int x, int y) {
int diff = (x - y);
return y + (diff & diff >> 31);
}
public static int max(int x, int y) {
int diff = (x - y);
return x - (diff & diff >> 31);
}
Method 1(Use XOR and comparison operator)
int
min(
int
x,
int
y)
{
return
y ^ ((x ^ y) & -(x < y));
}
/*Function to find maximum of x and y*/
int
max(
int
x,
int
y)
{
return
x ^ ((x ^ y) & -(x < y));
}
No comments:
Post a Comment