How would you solve this 'interview' question in D?

Steven Schveighoffer schveiguy at yahoo.com
Thu Jun 27 10:43:24 PDT 2013


On Wed, 26 Jun 2013 16:51:33 -0400, Gary Willoughby <dev at 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.

-Steve


More information about the Digitalmars-d-learn mailing list