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);
}
share
This is both off-topic on meta as well as on the main site. I'd suggest writing some unit tests yourself. – codesparkle Mar 8 at 12:57
In Java max(0, Integer.MIN_VALUE) returns with Integer.MIN_VALUE (-2147483648) instead of 0. – palacsint Mar 8 at 14:41

closed as off topic by codesparkle Mar 8 at 12:56

Questions on this site are expected to be discussion, support, and feature requests for Code Review - Stack Exchange. See the FAQ for guidance on how to improve it.

You must log in to answer this question.

Browse other questions tagged