Last active
December 15, 2015 00:28
-
-
Save charlespunk/5172916 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Write a method which finds the maximum of two numbers. You should not use if-else or any other comparision operator. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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