Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Last active December 15, 2015 00:28
Show Gist options
  • Save charlespunk/5172916 to your computer and use it in GitHub Desktop.
Save charlespunk/5172916 to your computer and use it in GitHub Desktop.
Write a method which finds the maximum of two numbers. You should not use if-else or any other comparision operator.
public static int findMax(int a, int b){
int sign_a = sign(a);
int sign_b = sign(b);
int sigh_a_minus_b = sign(a - b);
int different = sign_a ^ sign_b;
int result = 0;
result = (sign_a * a + sign_b * b) * different +
(sigh_a_minus_b * a + flip(sigh_a_minus_b) * b) * (1 - different);
return result;
}
public static int sign(int input){
return (input >> 31) & 0x1;
}
public static flip(int input){
return input ^ 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment