Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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;
    }


It’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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: