views:

191

answers:

1

Possible Duplicate:
Interview question: f(f(n)) == -n

Like I wrote above, implement a function whose prototype is

int foo(int n);

such that foo(foo(x)) returns -x

A: 
int foo(int n)
{
    static int called = 1;
    if (called == 2)
    {
        called = 1;
        return n;
    }
    else
    {
        called = 2;
        return -n;
    }
}
IVlad
i forgot to say : it's forbidden to use static \ global variables
Ohad
Well, that's too bad :). See if any of the answers in the duplicate question fit your requirements.
IVlad
i thought about other solution ( it was a challenge not homework! ) it includes function overloading...
Ohad
This might not work: x = foo(1); y = foo(2); z = foo(x);
Moron