Find maximum of two numbers without any comparison operator
public class MaxWithoutComparison
{
static int max (int a, int b)
{
int diff = a-b;
int isNegative = (diff>>31) & 0x1;
return a - isNegative * diff;
}
public static void main(String[] args)
{
System.out.println(max(5,3));
System.out.println(max(3,5));
System.out.println(max(2,2));
System.out.println(max(-1, 1));
System.out.println(max(-1, -4));
}
}
Got a thought to share or found a bug in the code? We'd love to hear from you: