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

John Colvin john.loughran.colvin at gmail.com
Thu Jun 27 05:38:23 PDT 2013


On Wednesday, 26 June 2013 at 20:51:35 UTC, Gary Willoughby 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

The question is ambiguous as to what they mean by -n. Do they 
mean the result of negation on the 32bit signed int, or do they 
mean the negative of the number represented by that int. this 
matters because -int.min evaluates to int.min due to wraparound.

So.. If we assume we want the proper mathematical negation:

Taking note that although the spec specifies n as a 32bit integer 
it says nothing about the signature of the function or the type 
of the result, we can just use implicit int->long

byte s(long n)
{
         return (n & 0x8000000000000000) ? -1 : 1;
}

long f(long x)
{
         if(x == 0)	return 0;
         if(x % 2)	return x + s(x);
         return s(x) - x;
}

unittest
{
         foreach(int n; int.min + 1 .. int.max)
         {
                 assert(f(f(n)) == -n);
         }
	assert(f(f(int.max)) == -int.max);
}


More information about the Digitalmars-d-learn mailing list