On Thursday, 27 June 2013 at 18:00:21 UTC, Steven Schveighoffer
wrote:
On Thu, 27 Jun 2013 13:43:24 -0400, Steven Schveighoffer
<schvei...@yahoo.com> wrote:
On Wed, 26 Jun 2013 16:51:33 -0400, Gary Willoughby
<d...@kalekold.net> wrote:
Just for a bit of fun, I saw this question posted on reddit
the other day and wondered how *you* would solve this in D?
http://stackoverflow.com/questions/731832/interview-question-ffn-n
int f(int x)
{
return x < 0 ? (x & 1 ? x+1 : -x+1) : (x & 1 ? x-1 : -x-1);
}
works for all but int.min, but -int.min == int.min, so, I'm
not sure what to do for that. Either change argument type for
long, in which case the result of f(f(int.min)) == int.max +
1LL, or special case int.min to return int.min.
I was wrong, it doesn't work for -1 also.
Hm...
I could special case that too... but I like the simplicity :)
-Steve
The trick is to move away from 0 in all cases (see my solution)