How would you solve this 'interview' question in D?
Steven Schveighoffer
schveiguy at yahoo.com
Thu Jun 27 11:46:47 PDT 2013
On Thu, 27 Jun 2013 14:09:11 -0400, John Colvin
<john.loughran.colvin at 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
More information about the Digitalmars-d-learn
mailing list