On Thu, 27 Jun 2013 14:09:11 -0400, John Colvin <john.loughran.col...@gmail.com> wrote:

The trick is to move away from 0 in all cases (see my solution)

Yes, but you still have to special case 0:

int f(int x)
{
   return x == 0 ? 0 : x > 0 ? (x & 1 ? x+1 : -x+1) : (x & 1 ? x-1 : -x-1);
}

Works for everything but int.max (and only works for int.min because -int.min == int.min). With long as parameters, it does the mathematically correct thing.

I think there isn't any other way to do it, you have to special case 0, and possibly the min/max.

-Steve

Reply via email to