No if/else, or >=<, or ternary(?) operators allowed.
This is disucssed in,
http://stackoverflow.com/questions/4772780/find-the-maximum-of-two-numbers-without-using-if-else-or-any-other-comparison-op
But no one seems to have posted the solution that I have. So wondering if this works for all inputs. (note that it avoids any multiplications)
int max(int i, int j) {
int m = (i-j) >> 31;
return (m & j) + ((~m) & i);
}
max(0, Integer.MIN_VALUE)
returns withInteger.MIN_VALUE
(-2147483648
) instead of0
. – palacsint Mar 8 at 14:41