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

Steven Schveighoffer schveiguy at yahoo.com
Thu Jun 27 11:00:20 PDT 2013


On Thu, 27 Jun 2013 13:43:24 -0400, Steven Schveighoffer  
<schveiguy at yahoo.com> wrote:

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

I was wrong, it doesn't work for -1 also.

Hm...

I could special case that too... but I like the simplicity :)

-Steve


More information about the Digitalmars-d-learn mailing list