Make delicious recipes!

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));
    }
}

Sample Execution
isNegative: 0
Max = 5

isNegative: 1
Max = 5

isNegative: 0
Max = 2

isNegative: 1
Max = 1

isNegative: 0
Max = -1







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal