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

Reply via email to