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

Jesse Phillips Jesse.K.Phillips+D at gmail.com
Wed Jun 26 21:35:26 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

Well, considering there is little to that specification:

int f(int num) {
     import std.exception;
     static called = false;
     enforce(num != int.min);
     if(!called) {
         called = true;
         return num;
     } else {
         called = false; // Only for unittesting
         return -num;
     }
}

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

int having the issue that not all numbers are representable in 
both +/-.


More information about the Digitalmars-d-learn mailing list