(no title)
pksadiq | 3 years ago
int mid(int x, int y) {
return (x/2 + y/2) + (1 & x & y);
}
would be a more readable solutionedit: Actually, this fails on mid(INT_MIN, INT_MAX) and possibly other mixed sign values (returns: -1, expected: 0 (or -1 is okay?), where the precise answer is -0.5)
more edit: The C standard says: When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded (This is often called ‘‘truncation toward zero’’).
So -1/2 should be 0.
nwellnhof|3 years ago
tiffanyh|3 years ago
https://en.cppreference.com/w/cpp/numeric/midpoint
Though it's odd this allows overflow.
abainbridge|3 years ago
abainbridge|3 years ago
bonzini|3 years ago