3 ms·
One of the solutions I came up with back in the day, without googling was this: int avg(int a, int b) { if ((a < 0) != (b < 0)) // not the same sig
by mojuba 4y ago
One of the solutions I came up with back in the day, without googling was this:
int avg(int a, int b) {
if ((a < 0) != (b < 0)) // not the same sign?
return (a + b) / 2;
else
return a + (b - a) / 2;
}
- DenisM 4y agoIt’s tricky. This will round (-2,-1) to -2, i.e. away from zero. For comparison, if we perform the canonical (a+b)/2 instead it will round to -1, i.e. towards zero. Now, the problem statement does not tell us how to round, so you’re technically correct, but the inconsistency bothers me.