847

A question I got on my last interview:

Design a function f, such that:

f(f(n)) == -n

Where n is a 32 bit signed integer; you can't use complex numbers arithmetic.

If you can't design such a function for the whole range of numbers, design it for the largest range possible.

Any ideas?

Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
Hrvoje Prgeša
  • 2,051
  • 5
  • 21
  • 36

120 Answers120

445

You didn't say what kind of language they expected... Here's a static solution (Haskell). It's basically messing with the 2 most significant bits:

f :: Int -> Int
f x | (testBit x 30 /= testBit x 31) = negate $ complementBit x 30
    | otherwise = complementBit x 30

It's much easier in a dynamic language (Python). Just check if the argument is a number X and return a lambda that returns -X:

def f(x):
   if isinstance(x,int):
      return (lambda: -x)
   else:
      return x()
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
viraptor
  • 33,322
  • 10
  • 107
  • 191
  • 23
    Cool, I love this... the same approach in JavaScript: var f = function(n) { return (typeof n == 'function') ? n() : function() { return -n; } } – Mark Renouf Apr 09 '09 at 02:17
  • It's probably just that my Haskell is very rusty, but have you checked that for (f 0)? It looks like that should produce the same result as (f 0x80000000), at least if we're dealing with 32-bit ints with wraparound arithmetic (on the negate operation). And that would be bad. – Darius Bacon Apr 09 '09 at 09:31
  • 11
    Would the average interviewer even know what a lambda construct *is*? – Jeremy Powell Aug 26 '09 at 21:00
  • Is there an equivalent implementation in C# for the lambda solution? – Alex Bagnolini May 24 '10 at 22:11
  • @Alex Bagnolini - probably not - you cannot have an "int or Func" return type that would compile without "dynamic". – viraptor May 25 '10 at 00:20
  • @viraptor The question doesn't specify the signature of the function though; it would work fine with dynamic or object as the parameter and return types. – Mark Rendle Aug 09 '11 at 17:49
  • 4
    Of course, such a type-cheating trick also works in Haskell, even though it's static: `class C a b | a->b where { f :: a->b }`; `instance C Int (()->Int) where { f=const.negate }`; `instance C (()->Int) Int where { f=($()) }`. – leftaroundabout Mar 16 '13 at 20:39
  • 4
    What? Where did you get the idea that typeof f(n) === 'function', especially, where n is a number and you expect a number returned? I don't understand how could an instance case apply here. I don't speak Python well, but in JS checking argument for a function type is plain wrong in this case. Only numeric solution applies here. f is a function, f(n) is number. – Harry Apr 25 '13 at 13:09
  • It doesn't work for all values in the domain of the function (or even all values excluding 0x80000000) - example: f (f (0x7ffff000 :: Int32)) = -2147479552 /= 0x7ffff000. I think the intention of the question was that it should work for the entire domain of the function. – a1kmm Jun 25 '13 at 06:37
378

How about:

f(n) = sign(n) - (-1)ⁿ * n

In Python:

def f(n): 
    if n == 0: return 0
    if n >= 0:
        if n % 2 == 1: 
            return n + 1
        else: 
            return -1 * (n - 1)
    else:
        if n % 2 == 1:
            return n - 1
        else:
            return -1 * (n + 1)

Python automatically promotes integers to arbitrary length longs. In other languages the largest positive integer will overflow, so it will work for all integers except that one.


To make it work for real numbers you need to replace the n in (-1)ⁿ with { ceiling(n) if n>0; floor(n) if n<0 }.

In C# (works for any double, except in overflow situations):

static double F(double n)
{
    if (n == 0) return 0;
    
    if (n < 0)
        return ((long)Math.Ceiling(n) % 2 == 0) ? (n + 1) : (-1 * (n - 1));
    else
        return ((long)Math.Floor(n) % 2 == 0) ? (n - 1) : (-1 * (n + 1));
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
RossFabricant
  • 12,364
  • 3
  • 41
  • 50
  • 10
    Broken for -1, because -1 * 0 is still 0 – Joel Coehoorn Apr 08 '09 at 21:25
  • 3
    No it isn't. f(-1) = 0. f(0) = 1 – 1800 INFORMATION Apr 08 '09 at 21:34
  • 5
    It is broken for 1 however. f(1) = 0. f(0) = 1 – 1800 INFORMATION Apr 08 '09 at 21:35
  • AFAIK, the modulus operator is not usually defined for negative integers... that may throw a wrench into your function. – rmeador Apr 08 '09 at 21:35
  • 1
    @1800: okay, he used the same technique as me but swapped when he adds/subtracts. Odd that it's voted higher when mine came first. – Joel Coehoorn Apr 08 '09 at 21:37
  • only by one though. My guess is that his is simpler to understand because he only has one answer in his post while you have two – 1800 INFORMATION Apr 08 '09 at 21:39
  • huh... I just created a solution of my own and then realized that it simplifies to this one :P – rmeador Apr 08 '09 at 21:43
  • @rmeador this is Python code, and modulus works on negatives. I'm trying to think of a way to fix it for 1. – RossFabricant Apr 08 '09 at 21:46
  • @Joel Coehoorn I stopped reading your reply after the part with state stored in f, since I felt that violated the spirit of the question; thus, I saw this one with this solution first. I've now upvoted yours as well. – Brian Campbell Apr 08 '09 at 22:00
  • 18
    Hmm, saving state with even and odd numbers, I should've thought of that. – Unknown Apr 08 '09 at 22:25
  • I was in the middle of trying to figure out a way to do it with odd and even numbers when I looked through the answers and saw that this one was already posted. Oh, well, I guess I was just a little slow. – Brian Campbell Apr 09 '09 at 00:10
  • 1
    Golf time: (JavaScript) var f = function(n){return n==0?0:n>0?(n%2!=0?n+1:-(n-1)):(n%2!=0?n-1:-(n+1))} – Mark Renouf Apr 09 '09 at 02:09
  • 2
    let me shorten your golf a little: function f(n){return !n?0:(n%2?n:-n)+(n>0?1:-1)} – cobbal Apr 09 '09 at 02:38
  • This is _a_ solution, but it seems hacky. Are there no better solutions to the interview question? – Juliet Apr 09 '09 at 16:55
  • This seems unnecessarily complex. It appears that the interview question is looking for the negative of the absolute value of the input. Why not just negate n if it is greater than 0, otherwise return it? – JoshL Apr 09 '09 at 21:24
  • @JoshL that works for f(n) == -n. Say if(n>0) return -n; else return n; If you say n = -3, then f(n) = -3, and f(f(n)) = -3, which is incorrect. – Davy8 Apr 09 '09 at 21:32
  • After the changes ("== 0.. return 0;" this really doesn't work for 1 or -1, or can someone explain why it does work for these two numbers? – Henry B Apr 12 '09 at 17:06
  • @PintSizedCat. Look again. f(1) = 2, f(2) = -1. f(-1) = -2, f(-2) = 1. – RossFabricant Apr 12 '09 at 23:24
  • 38
    I think the most important thing is not the actual function (there are infinitely many solutions), but the process by which you can construct such a function. – isekaijin Apr 13 '09 at 02:39
  • @rossfabricant: ahh, I missinterpreted the if n % 2 == 1: as if n % 2 == 0: – Henry B Apr 15 '09 at 14:53
  • No- it fails for n=1 and int.MinValue. But that's better than only positive or negative solutions provided by most of the other posts. – Joel Coehoorn May 05 '09 at 13:34
  • 1
    It works for all values but 2^(n - 1) - 1 if you use n bit integers. It works for n = 1: 1 => 2 [= 1 + 1] => -1 [= -1 * (2 - 1)]. – Daniel Brückner May 06 '09 at 17:41
  • I have a solution that works for the more logical and practical range of -1073741823 through to 1073741822. I don't think not working for "1" is particularly practical if it were a real-world solution. But then this is an interview question, so who am I to talk! – joshcomley May 30 '09 at 15:49
  • 1
    Python doesn't overflow. It just returns a long (arbitrarily long) value. – paperhorse Jun 20 '09 at 19:54
  • Equivalent in C# (works for all integers): static int F(int n) { if (n == 0) return 0; if (n < 0) return (n % 2 == 0) ? (n + 1) : (-1 * (n - 1)); else return (n % 2 == 0) ? (n - 1) : (-1 * (n + 1)); } – jpbochi Jul 28 '09 at 18:21
  • does the python code work as posted? i can't seem to make a java version work: static int f(int n) { if(n==0) return 0; if (n > 0) if (n % 2 == 1) return n + 1; else return -1 * (n - 1); else if (n % 2 == 1) return n - 1; else return -1 * (n + 1); } – Ray Tayek Aug 26 '09 at 15:28
  • @Ray Tayek: the problem is how java defines modulus of a negative number. to make it work in java, change `(n % 2 == 1)` to either this: `((n & 1) == 1)` or this: `(n % 2 != 0)` – Kip Aug 27 '09 at 02:13
  • 1
    You can use 2^32 as a carry value, since there is no -2^32 in 32 sign bit representation. Define explicitly with ifs that -1 ------> 2^32 -------> 1 and this is the best possible solution – mip Nov 09 '09 at 09:32
  • @EduardoLeón IMO this is also the important thing, but a minor correction: for a bounded range of integers the number of actual functions is bounded and not infinite. – infokiller Aug 08 '12 at 14:27
  • Ironically we had the same approach! Woot! This works for all but 2 values (1 and int.MinValue)... I posted one that works for all but 1 value (-1) http://stackoverflow.com/a/24728064/2057171 – Albert Renshaw Jul 14 '14 at 01:04
290

Here's a proof of why such a function can't exist, for all numbers, if it doesn't use extra information(except 32bits of int):

We must have f(0) = 0. (Proof: Suppose f(0) = x. Then f(x) = f(f(0)) = -0 = 0. Now, -x = f(f(x)) = f(0) = x, which means that x = 0.)

Further, for any x and y, suppose f(x) = y. We want f(y) = -x then. And f(f(y)) = -y => f(-x) = -y. To summarize: if f(x) = y, then f(-x) = -y, and f(y) = -x, and f(-y) = x.

So, we need to divide all integers except 0 into sets of 4, but we have an odd number of such integers; not only that, if we remove the integer that doesn't have a positive counterpart, we still have 2(mod4) numbers.

If we remove the 2 maximal numbers left (by abs value), we can get the function:

int sign(int n)
{
    if(n>0)
        return 1;
    else 
        return -1;
}

int f(int n)
{
    if(n==0) return 0;
    switch(abs(n)%2)
    {
        case 1:
             return sign(n)*(abs(n)+1);
        case 0:
             return -sign(n)*(abs(n)-1);
    }
}   

Of course another option, is to not comply for 0, and get the 2 numbers we removed as a bonus. (But that's just a silly if.)

ShreevatsaR
  • 38,402
  • 17
  • 102
  • 126
SurDin
  • 3,281
  • 4
  • 26
  • 28
  • 30
    I can't believe I had to read this far down to find a good procedural solution that handles negative numbers without resorting to global variables or tricks that obfuscate the code. If I could vote you up more than once, I would. – Kyle Simek May 10 '09 at 15:59
  • Nice observation, that there is an odd number of nonzero integers in any _n_ signed bits. – Andres Jaan Tack Jun 09 '10 at 05:18
  • This would be my answer too, but beware of the edge case `n = -2147483648` (minimum value); you can't `abs(n)` in that case, and the result will be undefined (or an exception). – Kirk Broadhurst Nov 29 '11 at 22:50
  • @a1kmm, his proof shows that if `f(0)=x` then `x=0`, so it shows that `f(0)=0`. As for the rest, I will have to think on it, but it looks like a valid argument that you will have to divide the numbers into groups of 4. Cause the only thing that I can think that would make it invalid is the fact that `x=y` (`x!=0`), but this can't happen as this would mean `f(f(x))=x` and not `-x`. – JPvdMerwe Jun 25 '13 at 13:15
  • @a1kmm: The proof does cover that case, though it could stand to be made more explicit. If f(0)≠-2³² (that's -2^{32}, represented as 0x80000000), then the above proof that f(0)=0 holds, as it shows that if f(0)=x, then x = -x. So suppose, as you suggest, that f(0)=-2³² . Then, f(-2³²)=f(f(0))=-0=0, so we've removed *two* numbers, and the remaining 2(mod 4) numbers must be divided into 4 equally-sized groups, which is impossible. (Note we can't have f(x)=-2³² for any other x≠0 and x≠-2³², because we'd need 0=f(-2³²)=f(f(x))=-x. So these two numbers 0 and -2³² are disconnected from the rest.) – ShreevatsaR Jun 25 '13 at 14:05
  • 1
    @a1kmm: Sorry, -2³² above should have been -2³¹. Anyway, the case where f(0)≠0 (and so f(0)=-2³¹) is actually the easier case, as we showed these two are disconnected from the rest. The other case we need to consider is that f(0)=0, but f(x)=-2³¹ for some x≠0, x≠-2³¹. In that case, f(-2³¹)=f(f(x))=-x (note -x can't be -2³¹, because no such x exists). Further let f(-x)=y. Then f(y)=f(f(-x))=x. Again y can't be -2³¹ (as f(y)=x, but f(-2³¹)=-x, and x is not 0). So, -2³¹=f(x)=f(f(y))=-y, which is impossible. So indeed 0 and -2³¹ must be disconnected from the rest (not the image of anything else). – ShreevatsaR Jun 25 '13 at 14:52
  • I have to disagree with you on this. All you need to do is take the input int, cast it to a bit array (or just read it in as one, if the language allows that), then group them into pairs based on the sign bit, then just pick another one of the bits - doesn't matter which one - then cycle through them. This will only work if the language allows signed zeros though. – will Jun 25 '13 at 19:51
  • 1
    @will There are no signed zeros, if (as I assume) we're talking about two's-complement 32-bit integers. – goffrie Jun 26 '13 at 00:49
  • @ShreevatsaR Absolutely. The argument of the answer is almost correct. From the question, it is not explicit what `-n` is supposed to mean if `n` is the negative number with no positive counterpart. But most languages ignore this kind of overflow and defines `-n == n` in that case. Now, looking at the proof of this answer above, we see that from `x == -x` we can not conclude that `x` is zero, only that `x` is zero or `0x80000000`. So either `f` fixes both these values, or it swaps them. So, the same conclusion you had. For other numbers than these two, the number is distinct from its opposite. – Jeppe Stig Nielsen Jun 28 '13 at 20:34
150

Thanks to overloading in C++:

double f(int var)
{
 return double(var);
} 

int f(double var)
{
 return -int(var);
}

int main(){
int n(42);
std::cout<<f(f(n));
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Özgür
  • 8,077
  • 2
  • 68
  • 66
  • 4
    Unfortunately, because of name mangling, the functions you call "f" actually have weirder names. – isekaijin Apr 11 '09 at 02:28
  • 1
    I've thought of something like that, but thinking in C, this was thrown away... good job! – Liran Orevi May 04 '09 at 15:47
  • @Rui Craverio: It wouldn't work in .NET 3.5+ because the author chose to use the var keyword as a variable name. – Kredns Jun 03 '09 at 21:40
  • @Lucas: .NET 3.5 doesn't have anything to do with the var keyword, you're confusing with C# 3.0 (which can target .NET 2+). And the var keyword they added is a contextual keyword, so it wouldn't cause any problem here as "var" isn't being used as a type. – Trillian Aug 12 '09 at 00:56
  • 75
    technically... this is not what the question demands. you defined 2 f() functions, f(int) and f(float) and the questions asks "Design a function f() ... " – elcuco Aug 25 '09 at 20:49
  • FACINATING!! THIS IS THE MOST SUCCINT SOLUTION – Egon May 18 '10 at 04:57
  • 4
    @elcuco Technically, of course, but logically it's one function with multiple overloads (you can do f(f(42)) with that). Since the definition doesn't say anything about parameters and return value, I can hardly accept it as a technical definition. – Mark Toman Jun 25 '13 at 15:04
137

Or, you could abuse the preprocessor:

#define f(n) (f##n)
#define ff(n) -n

int main()
{
  int n = -42;
  cout << "f(f(" << n << ")) = " << f(f(n)) << endl;
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
Skizz
  • 69,698
  • 10
  • 71
  • 108
  • So you'd be Konrad "Le Chiffre" Rudolph then? I'll get my coat. Yeah, I know about the whole "void main" thing, but adding a "return 0;" is just so much extra effort ;-) – Skizz Apr 09 '09 at 17:50
  • Re Skizz's comment: Now, that's taking the whole 'programmers are lazy' stereotype to a whole 'nother level! :-) – RobH Apr 09 '09 at 18:00
  • 25
    @Skizz, return 0 from main isn't required in c++ even with int return value... so by doing it right you actually type one less character! – Dan Olson Apr 10 '09 at 09:49
  • 10
    Skizz always abuses preprocessor :D – Arnis Lapsa Jul 29 '09 at 15:45
  • 23
    This is not a function ..so this is not a valid solution – smerlin Mar 18 '10 at 22:47
  • 3
    @smerlin: It's technically an inline function returning an inline function: the bodies of both are expanded at compile time, or rather just before. Can't get much more efficient than this. – Jon Purdy Apr 26 '10 at 16:11
  • @Clark (the recent editor): `return 0;` can be left out for `main ()` although some older compilers may generate a warning about this. It means that the application has no meaningful exit code. – Skizz Sep 13 '10 at 09:19
106

This is true for all negative numbers.

    f(n) = abs(n)

Because there is one more negative number than there are positive numbers for twos complement integers, f(n) = abs(n) is valid for one more case than f(n) = n > 0 ? -n : n solution that is the same same as f(n) = -abs(n). Got you by one ... :D

UPDATE

No, it is not valid for one case more as I just recognized by litb's comment ... abs(Int.Min) will just overflow ...

I thought about using mod 2 information, too, but concluded, it does not work ... to early. If done right, it will work for all numbers except Int.Min because this will overflow.

UPDATE

I played with it for a while, looking for a nice bit manipulation trick, but I could not find a nice one-liner, while the mod 2 solution fits in one.

    f(n) = 2n(abs(n) % 2) - n + sgn(n)

In C#, this becomes the following:

public static Int32 f(Int32 n)
{
    return 2 * n * (Math.Abs(n) % 2) - n + Math.Sign(n);
}

To get it working for all values, you have to replace Math.Abs() with (n > 0) ? +n : -n and include the calculation in an unchecked block. Then you get even Int.Min mapped to itself as unchecked negation does.

UPDATE

Inspired by another answer I am going to explain how the function works and how to construct such a function.

Lets start at the very beginning. The function f is repeatedly applied to a given value n yielding a sequence of values.

    n => f(n) => f(f(n)) => f(f(f(n))) => f(f(f(f(n)))) => ...

The question demands f(f(n)) = -n, that is two successive applications of f negate the argument. Two further applications of f - four in total - negate the argument again yielding n again.

    n => f(n) => -n => f(f(f(n))) => n => f(n) => ...

Now there is a obvious cycle of length four. Substituting x = f(n) and noting that the obtained equation f(f(f(n))) = f(f(x)) = -x holds, yields the following.

    n => x => -n => -x => n => ...

So we get a cycle of length four with two numbers and the two numbers negated. If you imagine the cycle as a rectangle, negated values are located at opposite corners.

One of many solution to construct such a cycle is the following starting from n.

 n                 => negate and subtract one
-n - 1 = -(n + 1)  => add one
-n                 => negate and add one
 n + 1             => subtract one
 n

A concrete example is of such an cycle is +1 => -2 => -1 => +2 => +1. We are almost done. Noting that the constructed cycle contains an odd positive number, its even successor, and both numbers negate, we can easily partition the integers into many such cycles (2^32 is a multiple of four) and have found a function that satisfies the conditions.

But we have a problem with zero. The cycle must contain 0 => x => 0 because zero is negated to itself. And because the cycle states already 0 => x it follows 0 => x => 0 => x. This is only a cycle of length two and x is turned into itself after two applications, not into -x. Luckily there is one case that solves the problem. If X equals zero we obtain a cycle of length one containing only zero and we solved that problem concluding that zero is a fixed point of f.

Done? Almost. We have 2^32 numbers, zero is a fixed point leaving 2^32 - 1 numbers, and we must partition that number into cycles of four numbers. Bad that 2^32 - 1 is not a multiple of four - there will remain three numbers not in any cycle of length four.

I will explain the remaining part of the solution using the smaller set of 3 bit signed itegers ranging from -4 to +3. We are done with zero. We have one complete cycle +1 => -2 => -1 => +2 => +1. Now let us construct the cycle starting at +3.

    +3 => -4 => -3 => +4 => +3

The problem that arises is that +4 is not representable as 3 bit integer. We would obtain +4 by negating -3 to +3 - what is still a valid 3 bit integer - but then adding one to +3 (binary 011) yields 100 binary. Interpreted as unsigned integer it is +4 but we have to interpret it as signed integer -4. So actually -4 for this example or Int.MinValue in the general case is a second fixed point of integer arithmetic negation - 0 and Int.MinValue are mapped to themselve. So the cycle is actually as follows.

    +3 =>    -4 => -3 => -4 => -3

It is a cycle of length two and additionally +3 enters the cycle via -4. In consequence -4 is correctly mapped to itself after two function applications, +3 is correctly mapped to -3 after two function applications, but -3 is erroneously mapped to itself after two function applications.

So we constructed a function that works for all integers but one. Can we do better? No, we cannot. Why? We have to construct cycles of length four and are able to cover the whole integer range up to four values. The remaining values are the two fixed points 0 and Int.MinValue that must be mapped to themselves and two arbitrary integers x and -x that must be mapped to each other by two function applications.

To map x to -x and vice versa they must form a four cycle and they must be located at opposite corners of that cycle. In consequence 0 and Int.MinValue have to be at opposite corners, too. This will correctly map x and -x but swap the two fixed points 0 and Int.MinValue after two function applications and leave us with two failing inputs. So it is not possible to construct a function that works for all values, but we have one that works for all values except one and this is the best we can achieve.

Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143
101

Using complex numbers, you can effectively divide the task of negating a number into two steps:

  • multiply n by i, and you get n*i, which is n rotated 90° counter-clockwise
  • multiply again by i, and you get -n

The great thing is that you don't need any special handling code. Just multiplying by i does the job.

But you're not allowed to use complex numbers. So you have to somehow create your own imaginary axis, using part of your data range. Since you need exactly as much imaginary (intermediate) values as initial values, you are left with only half the data range.

I tried to visualize this on the following figure, assuming signed 8-bit data. You would have to scale this for 32-bit integers. The allowed range for initial n is -64 to +63. Here's what the function does for positive n:

  • If n is in 0..63 (initial range), the function call adds 64, mapping n to the range 64..127 (intermediate range)
  • If n is in 64..127 (intermediate range), the function subtracts n from 64, mapping n to the range 0..-63

For negative n, the function uses the intermediate range -65..-128.

alt text

Boann
  • 48,794
  • 16
  • 117
  • 146
geschema
  • 2,464
  • 4
  • 30
  • 41
  • But of course! It's so obvious if your language actually supports complex numbers (although re-reading the question, it doesn't say it has to be a program at all). – Michael Myers Apr 09 '09 at 21:47
  • Oh wait, the question says no complex numbers. I retract my upvote. – Michael Myers Apr 09 '09 at 21:47
  • 4
    @geschema, what tool did you use to create those nice graphics? – jwfearn Apr 12 '09 at 17:24
  • 10
    Sorry, the question says explicitly no complex numbers. – Rui Craveiro Apr 13 '09 at 18:54
  • 6
    @Liran: I used OmniGraffle (Mac-only) – geschema May 05 '09 at 10:40
  • I'm taken in by the diagrams too :) – pjp Aug 25 '09 at 20:51
  • 40
    +1 I think this is the best answer. I don't think people read enough, because they all noted that the question said complex numbers could not be used. I read the entire thing, and you described the solution in complex numbers to set the stage for the non-complex solution to the question asked. Very nicely done. – jrista Sep 26 '09 at 02:00
  • 1
    @jrista all the solutions use a second dimension, which is all that 'complex numbers' really are (most use odd vs even, & above uses `float` vs `int`). The '4 element ring' that many answers describe necessitates 4 states, which can be represented as 2 dimensions each with 2 states. The *problem* with this answer is that it requires additional processing space (only 'works' for -64..63, yet needs -128..127 space) and doesn't explicitly state written formula! – Kirk Broadhurst Nov 29 '11 at 23:01
68

Works except int.MaxValue and int.MinValue

    public static int f(int x)
    {

        if (x == 0) return 0;

        if ((x % 2) != 0)
            return x * -1 + (-1 *x) / (Math.Abs(x));
        else
            return x - x / (Math.Abs(x));
    }

pictorial

Boann
  • 48,794
  • 16
  • 117
  • 146
Rodrick Chapman
  • 5,437
  • 2
  • 31
  • 32
  • Not sure why this was downvoted. For what inputs does it fail? – Rodrick Chapman Jun 27 '10 at 09:14
  • Why don't you use the signum function?!? – comonad Jul 09 '11 at 15:52
  • 1
    The image is really good. Send `0` to `0` and `-2147483648` to `-2147483648` since these two numbers are fixed points for the negation operator, `x => -x`. For the rest of the numbers, follow the arrows in the image above. As is clear from SurDin's answer and its comments, there will be two numbers, in this case `2147483647` and `-2147483647` with no other pair left to swap with. – Jeppe Stig Nielsen Jun 28 '13 at 21:22
  • It looks like a smiley - with lot of wrinkles – Anshul Mar 14 '14 at 07:04
50

The question doesn't say anything about what the input type and return value of the function f have to be (at least not the way you've presented it)...

...just that when n is a 32-bit integer then f(f(n)) = -n

So, how about something like

Int64 f(Int64 n)
{
    return(n > Int32.MaxValue ? 
        -(n - 4L * Int32.MaxValue):
        n + 4L * Int32.MaxValue);
}

If n is a 32-bit integer then the statement f(f(n)) == -n will be true.

Obviously, this approach could be extended to work for an even wider range of numbers...

Daniel LeCheminant
  • 50,583
  • 16
  • 120
  • 115
  • 2
    Yeah, I was working on a similar approach. You beat me to it though. +1 :) – jalf Apr 08 '09 at 21:57
  • 1
    Very clever! This is very close to (& effectively the same as) using complex numbers, which would be the obvious & ideal solution but it explicitly disallowed. Working outside the range of allowable numbers. – Kirk Broadhurst Aug 25 '09 at 22:34
49

for javascript (or other dynamically typed languages) you can have the function accept either an int or an object and return the other. i.e.

function f(n) {
    if (n.passed) {
        return -n.val;
    } else {
        return {val:n, passed:1};
    }
}

giving

js> f(f(10))  
-10
js> f(f(-10))
10

alternatively you could use overloading in a strongly typed language although that may break the rules ie

int f(long n) {
    return n;
}

long f(int n) {
    return -n;
}
cobbal
  • 69,903
  • 20
  • 143
  • 156
  • The latter doesn't mean the requirement of "a"(singular) function. :) – Drew Apr 08 '09 at 23:26
  • Remove the second half of the answer and this is a correct answer. – jmucchiello Apr 08 '09 at 23:59
  • @Drew which is why I mentioned that it may break the rules – cobbal Apr 09 '09 at 00:09
  • how about struct dummy { int n; }; int f(dummy d) { return -d.n; } dummy f(int n) { dummy d = { n }; return d; } . would be better protected against ambiguities. or using one function: variant f(variant v) { .... } similar to your javascript sample – Johannes Schaub - litb Apr 09 '09 at 02:04
  • that is indeed better; I was trying to keep it simple to highlight the main concept. – cobbal Apr 09 '09 at 02:06
  • a function is not supposed to keep any state. – nonopolarity May 14 '09 at 05:33
  • to define a math function to do this the same way is fairly easy too though, let f:ℚ→ℚ be defined as f(n) = n + 1/2 if n∈ℤ and -(n - 1/2) if n∉ℤ. Same thing really, no state being kept as they are different inputs (well, not the C one as it's 2 different functions). – cobbal May 14 '09 at 07:37
  • 2
    In JavaScript, a function is an object and so can keep a state. – Nosredna Jun 03 '09 at 21:00
  • 1
    IMO: function f(n){ return n.passed ? -n.val : {val:n, passed:1} } is more readable and shorter. – SamGoody Jun 25 '13 at 09:44
46

Depending on your platform, some languages allow you to keep state in the function. VB.Net, for example:

Function f(ByVal n As Integer) As Integer
    Static flag As Integer = -1
    flag *= -1

    Return n * flag
End Function

IIRC, C++ allowed this as well. I suspect they're looking for a different solution though.

Another idea is that since they didn't define the result of the first call to the function you could use odd/evenness to control whether to invert the sign:

int f(int n)
{
   int sign = n>=0?1:-1;
   if (abs(n)%2 == 0)
      return ((abs(n)+1)*sign * -1;
   else
      return (abs(n)-1)*sign;
}

Add one to the magnitude of all even numbers, subtract one from the magnitude of all odd numbers. The result of two calls has the same magnitude, but the one call where it's even we swap the sign. There are some cases where this won't work (-1, max or min int), but it works a lot better than anything else suggested so far.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 1
    I believe it does work for MAX_INT since that's always odd. It doesn't work for MIN_INT and -1. – Airsource Ltd May 05 '09 at 13:22
  • 9
    It's not a function if it has side effects. – nos Aug 07 '09 at 16:47
  • 12
    That may be true in math, but it's irrelevant in programming. So the question is whether they're looking for a mathematical solution or a programming solution. But given that it's for a programming job... – Ryan Lundy Aug 26 '09 at 20:47
  • +1 I was going to post one with in C with "static int x" implementing a FIFO with negation of the output. But this is close enough. – phkahler Feb 15 '10 at 02:39
  • 2
    @nos: Yes it is, it just isn't referentially transparent. – Clark Gaebel Sep 11 '10 at 03:49
  • @Randy Where was thread safety a requirement? But beyond that, which example? I expect your talking about the VB.Net Static variable. There is more to static in VB than there is in C++/C#. VB.Net compiles Static varibles within a function to be locked using the System.Threading.Monitor type, and so it **is** thread safe in a way that a similar C++/C# program would not be... at least in terms of two threads hitting the function at the same time. However, if you're trying to keep track of more than one number at a time: you're right. But again: I didn't see that in the requirements list. – Joel Coehoorn Jun 25 '13 at 17:28
27

Exploiting JavaScript exceptions.

function f(n) {
    try {
        return n();
    }
    catch(e) { 
        return function() { return -n; };
    }
}

f(f(0)) => 0

f(f(1)) => -1

Anurag
  • 140,337
  • 36
  • 221
  • 257
23

For all 32-bit values (with the caveat that -0 is -2147483648)

int rotate(int x)
{
    static const int split = INT_MAX / 2 + 1;
    static const int negativeSplit = INT_MIN / 2 + 1;

    if (x == INT_MAX)
        return INT_MIN;
    if (x == INT_MIN)
        return x + 1;

    if (x >= split)
        return x + 1 - INT_MIN;
    if (x >= 0)
        return INT_MAX - x;
    if (x >= negativeSplit)
        return INT_MIN - x + 1;
    return split -(negativeSplit - x);
}

You basically need to pair each -x => x => -x loop with a y => -y => y loop. So I paired up opposite sides of the split.

e.g. For 4 bit integers:

0 => 7 => -8 => -7 => 0
1 => 6 => -1 => -6 => 1
2 => 5 => -2 => -5 => 2
3 => 4 => -3 => -4 => 3
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Eclipse
  • 44,851
  • 20
  • 112
  • 171
21

A C++ version, probably bending the rules somewhat but works for all numeric types (floats, ints, doubles) and even class types that overload the unary minus:

template <class T>
struct f_result
{
  T value;
};

template <class T>
f_result <T> f (T n)
{
  f_result <T> result = {n};
  return result;
}

template <class T>
T f (f_result <T> n)
{
  return -n.value;
}

void main (void)
{
  int n = 45;
  cout << "f(f(" << n << ")) = " << f(f(n)) << endl;
  float p = 3.14f;
  cout << "f(f(" << p << ")) = " << f(f(p)) << endl;
}
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Skizz
  • 69,698
  • 10
  • 71
  • 108
  • Good idea. As an alternative, you could probably lose the struct and instead have one function return a pointer, the other function dereference and negate. – Imbue Apr 10 '09 at 09:39
20

x86 asm (AT&T style):

; input %edi
; output %eax
; clobbered regs: %ecx, %edx
f:
    testl   %edi, %edi
    je  .zero

    movl    %edi, %eax
    movl    $1, %ecx
    movl    %edi, %edx
    andl    $1, %eax
    addl    %eax, %eax
    subl    %eax, %ecx
    xorl    %eax, %eax
    testl   %edi, %edi
    setg    %al
    shrl    $31, %edx
    subl    %edx, %eax
    imull   %ecx, %eax
    subl    %eax, %edi
    movl    %edi, %eax
    imull   %ecx, %eax
.zero:
    xorl    %eax, %eax
    ret

Code checked, all possible 32bit integers passed, error with -2147483647 (underflow).

LiraNuna
  • 64,916
  • 15
  • 117
  • 140
19

This Perl solution works for integers, floats, and strings.

sub f {
    my $n = shift;
    return ref($n) ? -$$n : \$n;
}

Try some test data.

print $_, ' ', f(f($_)), "\n" for -2, 0, 1, 1.1, -3.3, 'foo' '-bar';

Output:

-2 2
0 0
1 -1
1.1 -1.1
-3.3 3.3
foo -foo
-bar +bar
FMc
  • 41,963
  • 13
  • 79
  • 132
  • But it doesn't keep it an int. You are essentially storing global variable data in the int "n" itself... except it's not an int otherwise you couldn't do that. For example if `n` was a string I could make 548 becomes "First_Time_548" and then the next time it runs through the function... if (prefix == First_Time_") replace "First_Time_" with "-" – Albert Renshaw Jul 13 '14 at 04:49
  • @AlbertRenshaw Not sure where you get those ideas. (1) There are definitely no global variables involved here. (2) If you give the function an int, you'll get an int back -- or a reference to an int, if you call the function an odd number of times. (3) Perhaps most fundamentally, **this is Perl**. For all practical purposes, ints and strings are fully interchangeable. Strings that like look like numbers will function perfectly well as numbers in most contexts, and numbers will happily stringify whenever asked. – FMc Jul 13 '14 at 14:50
  • Sorry I don't know much perl it seemed you were using a global array haha – Albert Renshaw Jul 13 '14 at 17:50
19

Uses globals...but so?

bool done = false
f(int n)
{
  int out = n;
  if(!done)
  {  
      out = n * -1;
      done = true;
   }
   return out;
}
teeks99
  • 3,585
  • 2
  • 30
  • 38
  • 3
    Not sure that this was the intention of the question asker, but +1 for "thinking out of the box". – Liran Orevi May 04 '09 at 15:40
  • 5
    Instead of conditionally saying "done = true", you should always say "done = !done", that way your function can be used more than once. – Chris Lutz Jul 27 '09 at 05:27
  • @Chris, since setting done to true is inside of an if(!done) block, it's equivalent to done=!done, but !done doesn't need to be computed (or optimized out by the compiler, if it's smart enough). – nsayer Apr 26 '10 at 16:06
  • This is the first thing that comes to mind for me. I thought this was cheating. @nsayer, Chris is talking about putting done = !done _outside_ the if statement. – Ponkadoodle Jun 27 '10 at 04:06
  • 1
    My first thought was also to solve this using a global variable, even though it kind of felt like cheating for this particular question. I would however argue that a global variable solution is the best solution given the specifications in the question. Using a global makes it very easy to understand what is happening. I would agree that a done != done would be better though. Just move that outside the if clause. – Alderath Jul 12 '10 at 07:45
  • 3
    Technically, anything that maintains state is not a function, but a state machine. By [definition](http://en.wikipedia.org/wiki/Function_%28mathematics%29), a function always gives the same output for the same input. – Ted Hopp Dec 19 '11 at 07:14
  • @userunknown that's ridiculous anyways.... thread safe doesn't even matter in this case since "n" MUST be a global variable for this to work anyways. – Albert Renshaw Jul 13 '14 at 04:59
18

Nobody ever said f(x) had to be the same type.

def f(x):
    if type(x) == list:
        return -x[0]
    return [x]


f(2) => [2]
f(f(2)) => -2
Dial Z
  • 675
  • 6
  • 8
16

Here is a solution that is inspired by the requirement or claim that complex numbers can not be used to solve this problem.

Multiplying by the square root of -1 is an idea, that only seems to fail because -1 does not have a square root over the integers. But playing around with a program like mathematica gives for example the equation

(18494364652+1) mod (232-3) = 0.

and this is almost as good as having a square root of -1. The result of the function needs to be a signed integer. Hence I'm going to use a modified modulo operation mods(x,n) that returns the integer y congruent to x modulo n that is closest to 0. Only very few programming languages have suc a modulo operation, but it can easily be defined. E.g. in python it is:

def mods(x, n):
    y = x % n
    if y > n/2: y-= n
    return y

Using the equation above, the problem can now be solved as

def f(x):
    return mods(x*1849436465, 2**32-3)

This satisfies f(f(x)) = -x for all integers in the range [-231-2, 231-2]. The results of f(x) are also in this range, but of course the computation would need 64-bit integers.

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
Accipitridae
  • 3,136
  • 19
  • 9
16

I'm not actually trying to give a solution to the problem itself, but do have a couple of comments, as the question states this problem was posed was part of a (job?) interview:

  • I would first ask "Why would such a function be needed? What is the bigger problem this is part of?" instead of trying to solve the actual posed problem on the spot. This shows how I think and how I tackle problems like this. Who know? That might even be the actual reason the question is asked in an interview in the first place. If the answer is "Never you mind, assume it's needed, and show me how you would design this function." I would then continue to do so.
  • Then, I would write the C# test case code I would use (the obvious: loop from int.MinValue to int.MaxValue, and for each n in that range call f(f(n)) and checking the result is -n), telling I would then use Test Driven Development to get to such a function.
  • Only if the interviewer continues asking for me to solve the posed problem would I actually start to try and scribble pseudocode during the interview itself to try and get to some sort of an answer. However, I don't really think I would be jumping to take the job if the interviewer would be any indication of what the company is like...

Oh, this answer assumes the interview was for a C# programming related position. Would of course be a silly answer if the interview was for a math related position. ;-)

peSHIr
  • 6,279
  • 1
  • 34
  • 46
  • 7
    You are lucky they asked for 32 int, if it was 64 bit the interview will never continue after you run the tests ;-) – alex2k8 Apr 13 '09 at 12:39
  • Indeed, if I would even get to a point to actually write that test and run it during an interview. ;-) My point: I would try not to get to that point in an interview at all. Programming is more of "a way of thinking" than "how does he write lines of code" in my opinion. – peSHIr Apr 14 '09 at 09:26
  • 7
    Don't follow this advice in an actual interview. The interviewer expects you to actually answer the question. Questioning the relevance of the question won't buy you anything but it may annoy the interviewer. Designing a trivial test does not bring you any step closer to the answer, and you can't run it in the interview. If you get extra information (32 bit), try to figure out how that could be useful. – Stefan Haustein Jun 25 '13 at 08:23
  • 1
    An interviewer that gets annoyed when I ask for more information (while possibly questioning the relevance of his question in the process) is not an interviewer I necessarily want to be working for/with. So I will keep asking questions like that in interviews. If they don't like it, I'll probably end the interview to stop wasting both of our time any further. Don't like the "I was only following orders" mind set one bit. Do you..? – peSHIr Aug 16 '13 at 11:08
16

I would you change the 2 most significant bits.

00.... => 01.... => 10.....

01.... => 10.... => 11.....

10.... => 11.... => 00.....

11.... => 00.... => 01.....

As you can see, it's just an addition, leaving out the carried bit.

How did I got to the answer? My first thought was just a need for symmetry. 4 turns to get back where I started. At first I thought, that's 2bits Gray code. Then I thought actually standard binary is enough.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
eipipuz
  • 563
  • 1
  • 7
  • 16
  • The problem with this approach is that it doesn't work with two's compliment negative numbers (which is what every modern CPU uses). That's why I deleted my identical answer. – Tamas Czinege Nov 23 '09 at 16:25
  • The question specified 32-bit signed integers. This solution does not work for two's-complement or one's-complement representations of the 32-bit signed integers. It will only work for sign-and-magnitude representations, which are very uncommon in modern computers (other than floating point numbers). – Jeffrey L Whitledge Nov 23 '09 at 17:11
  • 1
    @DrJokepu - Wow, after six months--jinx! – Jeffrey L Whitledge Nov 23 '09 at 17:12
  • Don't you just need to convert the numbers to sign-and-magnitude representation inside the function, perform the transformation, then convert back to whatever the native integer representation is before returning it? – Bill Michell Nov 23 '10 at 23:43
  • I like that you basically implemented complex numbers by introducing an imaginary bit :) – jabirali Dec 07 '11 at 09:14
13

C# for a range of 2^32 - 1 numbers, all int32 numbers except (Int32.MinValue)

    Func<int, int> f = n =>
        n < 0
           ? (n & (1 << 30)) == (1 << 30) ? (n ^ (1 << 30)) : - (n | (1 << 30))
           : (n & (1 << 30)) == (1 << 30) ? -(n ^ (1 << 30)) : (n | (1 << 30));

    Console.WriteLine(f(f(Int32.MinValue + 1))); // -2147483648 + 1
    for (int i = -3; i <= 3  ; i++)
        Console.WriteLine(f(f(i)));
    Console.WriteLine(f(f(Int32.MaxValue))); // 2147483647

prints:

2147483647
3
2
1
0
-1
-2
-3
-2147483647
Pop Catalin
  • 61,751
  • 23
  • 87
  • 115
  • This also doesn't work for f(0) which is 1073741824. f(1073741824) = 0. f(f(1073741824)) = 1073741824 – Dinah Aug 26 '09 at 16:02
  • You can generally prove that for a two's complement integer type of any bit size, the function **has to** not work for at least two input values. – slacker Aug 27 '10 at 16:15
12

Essentially the function has to divide the available range into cycles of size 4, with -n at the opposite end of n's cycle. However, 0 must be part of a cycle of size 1, because otherwise 0->x->0->x != -x. Because of 0 being alone, there must be 3 other values in our range (whose size is a multiple of 4) not in a proper cycle with 4 elements.

I chose these extra weird values to be MIN_INT, MAX_INT, and MIN_INT+1. Furthermore, MIN_INT+1 will map to MAX_INT correctly, but get stuck there and not map back. I think this is the best compromise, because it has the nice property of only the extreme values not working correctly. Also, it means it would work for all BigInts.

int f(int n):
    if n == 0 or n == MIN_INT or n == MAX_INT: return n
    return ((Math.abs(n) mod 2) * 2 - 1) * n + Math.sign(n)
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Craig Gidney
  • 17,763
  • 5
  • 68
  • 136
12

Nobody said it had to be stateless.

int32 f(int32 x) {
    static bool idempotent = false;
    if (!idempotent) {
        idempotent = true;
        return -x;
    } else {
        return x;
    }
}

Cheating, but not as much as a lot of the examples. Even more evil would be to peek up the stack to see if your caller's address is &f, but this is going to be more portable (although not thread safe... the thread-safe version would use TLS). Even more evil:

int32 f (int32 x) {
    static int32 answer = -x;
    return answer;
}

Of course, neither of these works too well for the case of MIN_INT32, but there is precious little you can do about that unless you are allowed to return a wider type.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Christopher Smith
  • 5,372
  • 1
  • 34
  • 18
  • you can 'upgrade' it to ask about the address (yes, you must get it by ref\ as a pointer) - in C, for example: int f(int& n) { static int* addr = &n; if (addr == &n) { return -n; } return n; } – IUnknownPointer Jun 28 '10 at 08:27
11

I could imagine using the 31st bit as an imaginary (i) bit would be an approach that would support half the total range.

llamaoo7
  • 4,051
  • 2
  • 22
  • 22
10

works for n= [0 .. 2^31-1]

int f(int n) {
  if (n & (1 << 31)) // highest bit set?
    return -(n & ~(1 << 31)); // return negative of original n
  else
    return n | (1 << 31); // return n with highest bit set
}
MartinStettner
  • 28,719
  • 15
  • 79
  • 106
10

The problem states "32-bit signed integers" but doesn't specify whether they are twos-complement or ones-complement.

If you use ones-complement then all 2^32 values occur in cycles of length four - you don't need a special case for zero, and you also don't need conditionals.

In C:

int32_t f(int32_t x)
{
  return (((x & 0xFFFFU) << 16) | ((x & 0xFFFF0000U) >> 16)) ^ 0xFFFFU;
}

This works by

  1. Exchanging the high and low 16-bit blocks
  2. Inverting one of the blocks

After two passes we have the bitwise inverse of the original value. Which in ones-complement representation is equivalent to negation.

Examples:

Pass |        x
-----+-------------------
   0 | 00000001      (+1)
   1 | 0001FFFF (+131071)
   2 | FFFFFFFE      (-1)
   3 | FFFE0000 (-131071)
   4 | 00000001      (+1)

Pass |        x
-----+-------------------
   0 | 00000000      (+0)
   1 | 0000FFFF  (+65535)
   2 | FFFFFFFF      (-0)
   3 | FFFF0000  (-65535)
   4 | 00000000      (+0)
finnw
  • 47,861
  • 24
  • 143
  • 221
  • 1
    What about byte-order across different architectures? – Steven Aug 25 '09 at 21:02
  • 1
    All the arithmetic is 32-bit. I do not manipulate individual bytes, so byte order will not affect it. – finnw Aug 25 '09 at 22:01
  • This sounds pretty close. You can assume the input is 2-complement. So you convert to the sign bit representation. Now depending on the last bit, you flip the first bit and the last bit or just the last bit. Basically you negate only even numbers and cycle even/odd all the time. So you get back from odd to odd and even to even after 2 calls. At the end you convert back to 2-complement. Have posted the code for this somewhere below. – Stefan Haustein Jun 25 '13 at 08:29
9

:D

boolean inner = true;

int f(int input) {
   if(inner) {
      inner = false;
      return input;
   } else {
      inner = true;
      return -input;
   }
}
Drew
  • 15,158
  • 17
  • 68
  • 77
  • 5
    Might also get you a discussion on why global variables are bad if they don't kick you out of the interview right there! – palswim Aug 12 '10 at 22:49
9
return x ^ ((x%2) ? 1 : -INT_MAX);
7

I'd like to share my point of view on this interesting problem as a mathematician. I think I have the most efficient solution.

If I remember correctly, you negate a signed 32-bit integer by just flipping the first bit. For example, if n = 1001 1101 1110 1011 1110 0000 1110 1010, then -n = 0001 1101 1110 1011 1110 0000 1110 1010.

So how do we define a function f that takes a signed 32-bit integer and returns another signed 32-bit integer with the property that taking f twice is the same as flipping the first bit?

Let me rephrase the question without mentioning arithmetic concepts like integers.

How do we define a function f that takes a sequence of zeros and ones of length 32 and returns a sequence of zeros and ones of the same length, with the property that taking f twice is the same as flipping the first bit?

Observation: If you can answer the above question for 32 bit case, then you can also answer for 64 bit case, 100 bit case, etc. You just apply f to the first 32 bit.

Now if you can answer the question for 2 bit case, Voila!

And yes it turns out that changing the first 2 bits is enough.

Here's the pseudo-code

1. take n, which is a signed 32-bit integer.
2. swap the first bit and the second bit.
3. flip the first bit.
4. return the result.

Remark: The step 2 and the step 3 together can be summerised as (a,b) --> (-b, a). Looks familiar? That should remind you of the 90 degree rotation of the plane and the multiplication by the squar root of -1.

If I just presented the pseudo-code alone without the long prelude, it would seem like a rabbit out of the hat, I wanted to explain how I got the solution.

Yoo
  • 17,526
  • 6
  • 41
  • 47
  • 6
    Yes it's an interesting problem. You know your math. But this is a computer science problem. So you need to study computers. Sign-magnitude representation is allowable but it went out of style around 60 years ago. 2's-complement is most popular. – Windows programmer Apr 21 '09 at 03:41
  • 5
    Here's what your function does to the two bits when applied twice: (a,b) --> (-b, a) --> (-a, -b). But, we are trying to get to (-a, b), not (-a, -b). – buti-oxa May 31 '09 at 15:30
  • @buti-oxa, you are right. The two bits operation should go like: 00 -> 01 -> 10 -> 11 -> 00. But then my algorithm assumes sign-magnitude representation which is unpopular now, as Windows programmer said, so I think my algorithm is of little use. – Yoo Jun 01 '09 at 07:13
  • So can't he just do the steps twice instead of once? – Nosredna Jun 03 '09 at 21:02
  • 4
    buti-oxa is entirely right: the function doesn't even flip the first bit after two invocations, it flips the first two bits. Flipping all the bits is closer to what 2's complement does, but it's not exactly right. – redtuna Jun 22 '10 at 20:40
6

That's easy!

Every number is mapped to another in cycles of 4, where the needed condition holds.

Example:

The rules are:

  • 0 → 0

  • ±2³¹ → ±2³¹

  • odd → even, even → -odd:

    forall k, 0 < k < 2³⁰: (2k-1) → (2k) → (-2k+1) → (-2k) → (2k-1)

The only not matching values are ±(2³¹-1), because there are only two. There have to be two that cannot match, because there are only a multiple of four of numbers in a two's-complement system where 0 and ±2³¹ are already reserved.

In a one's complement system, there exist +0 and -0. There we go:

forall k, 0 < k < 2³⁰: (+2k) → (+2k+1) → (-2k) → (-2k-1) → (+2k)

comonad
  • 5,134
  • 2
  • 33
  • 31
6

In PHP

function f($n) {
    if(is_int($n)) {
        return (string)$n;
    }
    else {
        return (int)$n * (-1);
    }
}

I'm sure you can understand the spirit of this method for other languages. I explicitly casted back to int to make it more clear for people who don't use weakly typed languages. You'd have to overload the function for some languages.

The neat thing about this solution is it works whether you start with a string or an integer, and doesn't visibly change anything when returning f(n).

In my opinion, the interviewer is asking, "does this candidate know how to flag data to be operated on later," and, "does this candidate know how to flag data while least altering it?" You can do this with doubles, strings, or any other data type you feel like casting.

Frank Crook
  • 1,466
  • 12
  • 19
  • But of course, using hacks like this in real code is a terrible idea. If you need to store state with your data, create a new type like (s, a), and use a binding operator to work with only the result. (This is very similar to Haskell's state monad, but not the same.) – jrockway Aug 26 '09 at 21:02
5

Easy Python solution made possible by the fact that there were no restrictions on what f(x) was supposed to output, only f(f(x)):

def f(x):
    return (isinstance(x, tuple) and -x[0]) or (x,)
rein
  • 32,967
  • 23
  • 82
  • 106
5

I have another solution that works half of the time:

def f(x):
    if random.randrange(0, 2):
        return -x
    return x
Alexandru
  • 25,070
  • 18
  • 69
  • 78
3

How about this?

int nasty(int input)
{
    return input + INT_MAX/2;
}
Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • Hmm... I believe I made a typo. Essentially the point is to overflow the integer variable until it is in negative territory. But I believe I screwed something up here.. ignore. – Billy ONeal Jan 30 '10 at 19:45
  • Interesting solution, I had a similar one, too. But I realized, it isn't a solution. Talking about bytes: 1+63=64, 64+63=127. Even 127+1 = -128, not -1. Why is this wrong solution upvoted? – user unknown May 30 '11 at 04:13
  • @user: I don't know myself. I believe I acknowledged that I screwed something up in a comment. I think it was upvoted because the point is sound even if this exact code isn't perfect. I would have deleted this answer but decided not to because it's CW. – Billy ONeal May 30 '11 at 04:19
3

Although the question said n had to be a 32 bit int, it did not say the parameter or return type had to be a 32 bit int. This should compile in java--in c you could get rid of the != 0

private final long MAGIC_BIT=1<<38;
long f(long n) {
    return n & MAGIC_BIT != 0 ? -(n & !MAGIC_BIT) : n | MAGIC_BIT;
}

edit:

This actually makes for a really good interview question. The best ones are ones difficult or impossible to answer because it forces people to think it through and you can watch and look for:

  • Do they just give up?
  • Do they say it's stupid?
  • Do they try unique approaches?
  • Do they communicate with you while they are working on the problem?
  • Do they ask for further refinements of the requirements?

etc.

Never just answer behavioral questions unless you have a VERY GOOD answer. Always be pleasant and try to involve the questioner. Don't get frustrated and don't give up early! If you really aren't getting anywhere, try something totally illegal that could work, you'll get nearly full credit.

Bill K
  • 62,186
  • 18
  • 105
  • 157
3

Using the information given in the question, you can

  1. Convert from 2-complement to sign bit representation
  2. If the last bit is set, flip the sign bit and the last bit; otherwise, flip just the last bit
  3. Convert back to 2-complement.

So you basically go odd -> even -> odd or even -> odd -> even, and change the sign only for even numbers. The only number this does not work for is -2^31

Code:

function f(x) {
  var neg = x < 0;
  x = Math.abs(x) ^ 1;
  if (x & 1) {
    neg = !neg;
  }
  return neg ? -x : x;
}
Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
3

This is also a solution (but we are bending the rules a little bit):

def f(n):
    if isinstance(n,int):
        return str(n)
    else:
        return -int(n)
asmaier
  • 11,132
  • 11
  • 76
  • 103
3

I think the answer to these kind of questions are best explained visually by using diagrams. When we disregard zero, then we can partition the integers in small sets of 4 numbers:

 1  → 2    3  → 4    5  → 6
 ↑    ↓    ↑    ↓    ↑    ↓   ...
-2 ← -1   -4 ← -3   -6 ← -5

This is pretty easy to translate to code. Note that even numbers change sign, and the odd numbers are increased or decreased by 1. In C# it would look like this:

public static int f(int x)
{
    if(x == 0)
        return 0;

    if(x > 0)
        return (x % 2 == 0) ? -x+1 : x+1;

    // we know x is negative at this point
    return (x % 2 == 0) ? -x-1 : x-1;
}

Of course you can shorten this method by using clever tricks, but I think this code explains itself best.

Then about the range. The 32-bit integers range from -2^31 upto 2^31-1. The numbers 2^31-1, -2^31-1 and -2^31 fall outside of the range of f(x) because the number 2^31 is missing.

Elian Ebbing
  • 18,779
  • 5
  • 48
  • 56
3
  1. Convert n to Sign-and-magnitude representation;
  2. Add 1/4 of a range;
  3. Convert back.

    #define STYPE int
    STYPE sign_bit = (unsigned STYPE) 1 &lt&lt ( sizeof ( STYPE ) * 8  - 1 );
    STYPE f ( STYPE f )
    {
        unsigned STYPE smf = f > 0 ? f : -f | sign_bit;
        smf += sign_bit >> 1;
        return smf & sign_bit ? -( smf & ~sign_bit ) : smf;
    }
3
int f( int n ){
    return n==0?0:(n&1?n:-n)+(n<0?-1:1);
}
mateusza
  • 5,341
  • 2
  • 24
  • 20
3

Mine gives the right answer...50% of the time, all the time.

int f (int num) {
    if (rand () / (double) RAND_MAX > 0.5)
         return ~num + 1;
    return num;
}
user unknown
  • 35,537
  • 11
  • 75
  • 121
Dan Loewenherz
  • 10,879
  • 7
  • 50
  • 81
2

Golfing it in coffeescript:

f = (n)-> -n[0] or [n]
Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
2

Here's a short Python answer:

def f(n):
  m = -n if n % 2 == 0 else n
  return m + sign(n)

General Case

A slight tweak to the above can handle the case where we want k self-calls to negate the input -- for example, if k = 3, this would mean g(g(g(n))) = -n:

def g(n):
  if n % k: return n + sign(n)
  return -n + (k - 1) * sign(n)

This works by leaving 0 in place and creating cycles of length 2 * k so that, within any cycle, n and -n are distance k apart. Specifically, each cycle looks like:

N * k + 1, N * k + 2, ... , N * k + (k - 1), - N * k - 1, ... , - N * k - (k - 1)

or, to make it easier to understand, here are example cycles with k = 3:

1, 2, 3, -1, -2, -3
4, 5, 6, -4, -5, -6

This set of cycles maximizes the ranges of inputs that will work within any machine type centered around zero, such as signed int32 or signed int64 types.

Analysis of compatible ranges

The map x -> f(x) in fact must form cycles of length 2 * k, where x = 0 is a special case 1-length cycle since -0 = 0. So the problem for general k is solvable if and only if the range of the input - 1 (to compensate for 0) is a multiple of 2 * k, and the positive and negative ranges are opposites.

For signed integer representations, we always have a smallest negative number with no positive counterpart in the range, so the problem becomes unsolveable on the complete range. For example, a signed char has range [-128, 127], so it's impossible for f(f(-128)) = 128 within the given range.

Tyler
  • 28,498
  • 11
  • 90
  • 106
2

Lua:

function f(n)
    if type(n) == "number" then
        return (-number) .. ""
    else
        return number + 0
    end
end
RCIX
  • 38,647
  • 50
  • 150
  • 207
2
f(n) { return -1 * abs(n) }

How can I handle overflow problems with this? Or am I missing the point?

Joe Phillips
  • 49,743
  • 32
  • 103
  • 159
  • you always return negative values, even if the input is negative – SilentGhost Apr 08 '09 at 21:50
  • 1
    Given the requirements of the question, that's probably an adequate response. It doesn't say that f(n) has to return a different value. The question is a puzzle, so you look for the exploits (loopholes) that would make a feasible solution. – JasonTrue Apr 08 '09 at 22:14
  • @Jason: The trouble is that for a negative input n, f(f(n)) should return a positive number (according to the question) which your solution fails to do since it always returns a negative number. – David Archer Apr 08 '09 at 23:13
  • Oh wow, I misunderstood the original question. I thought it was supposed to always return a negative. I didn't read the dash as "opposite" – Joe Phillips Apr 08 '09 at 23:43
  • Open to interpretation I think. If the question intended that it should return "the opposite" then it should have clarified that by giving a second example where f(f(-n)) == n. d03boy's answer works correctly for the question as it was stated IMO. – GrahamS Apr 15 '09 at 17:06
  • 3
    In your case, f(f(-1)) = f(1) = -1. Therefore f(f(n)) = n, for n<0. – Steven Aug 25 '09 at 19:07
  • 1
    Works for nearly 50% of the inputs. Is reproducable and threadsafe. :) There are inferior solutions which got more upvotes. :) – user unknown May 30 '11 at 04:21
2

A bizarre and only slightly-clever solution in Scala using implicit conversions:

sealed trait IntWrapper {
  val n: Int
}

case class First(n: Int) extends IntWrapper
case class Second(n: Int) extends IntWrapper
case class Last(n: Int) extends IntWrapper

implicit def int2wrapper(n: Int) = First(n)
implicit def wrapper2int(w: IntWrapper) = w.n

def f(n: IntWrapper) = n match {
  case First(x) => Second(x)
  case Second(x) => Last(-x)
}

I don't think that's quite the right idea though.

user unknown
  • 35,537
  • 11
  • 75
  • 121
Daniel Spiewak
  • 54,515
  • 14
  • 108
  • 120
2

Clojure solution:

(defmacro f [n]
  (if (list? n) `(- ~n) n))

Works on positive and negative integers of any size, doubles, and ratios too!

Brian Carper
  • 71,150
  • 28
  • 166
  • 168
1

Some were similar but just thought I would write down my first idea (in C++)

#include <vector>

vector<int>* f(int n)
{
  returnVector = new vector<int>();
  returnVector->push_back(n);
  return returnVector;
}

int f(vector<int>* n) { return -(n->at(0)); }

Just using overloading to cause f(f(n)) to actually call two different functions

Graphics Noob
  • 9,790
  • 11
  • 46
  • 44
1

JavaScript one-liner:

function f(n) { return ((f.f = !f.f) * 2 - 1) * n; }
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
1

Another way is to keep the state in one bit and flip it with care about binary representation in case of negative numbers... Limit is 2^29

int ffn(int n) {

    n = n ^ (1 << 30); //flip the bit
    if (n>0)// if negative then there's a two's complement
    {
        if (n & (1<<30))
        {
            return n;
        }
        else
        {
            return -n;
        }
    }
    else
    {
        if (n & (1<<30))
        {
            return -n;
        }
        else
        {
            return n;
        }
    }


}
Alin
  • 61
  • 4
1
number f( number n)
{
  static count(0);
  if(count > 0) return -n;
  return n;
}

f(n) = n

f(f(n)) = f(n) = -n
sth
  • 222,467
  • 53
  • 283
  • 367
Sam
  • 694
  • 4
  • 6
1
int f(int n) {
    return ((n>0)? -1 : 1) * abs(n);
}
Steven
  • 13,501
  • 27
  • 102
  • 146
1

How about this:

do
    local function makeFunc()
        local var
        return function(x)
            if x == true then
                return -var
            else
                var = x
                return true
            end
        end

    end
    f = makeFunc()
end
print(f(f(20000)))
RCIX
  • 38,647
  • 50
  • 150
  • 207
1
f(n) { return IsWholeNumber(n)? 1/n : -1/n }
Peter
  • 47,963
  • 46
  • 132
  • 181
1

Well, I am neither a math, nor a programming wizz, but isn't this pretty easy?

int f(int i) {
    static bool b;
    if (b) {
        b = !b;
        return i;
    } else {
        b = !b;
        return -i;
    }
}

Tested with big and small positive and negative values, INT_MIN, INT_MAX, it seems to work... Can be made thread safe if that is a concern, it wasn't a part of the assignment though.

Or maybe I am missing something?

dtech
  • 47,916
  • 17
  • 112
  • 190
  • I wouldn't expect this to be an acceptable answer. For example, imagine this: ```var x = f(1), y = f(2); console.log(f(x));``` – kybernetikos Jun 25 '13 at 08:46
  • @kybernetikos: the condition was `f(f(n)) == -n` - NOTICE the format of the call, making it impossible to achieve what your scenario achieves. If you care that much about calling it like you do - just create a wrapper method that does the nested call for you... – dtech Jun 25 '13 at 11:40
1

C++

struct Value
{
  int value;
  Value(int v) : value(v) {}
  operator int () { return -value; }
};


Value f(Value input)
{
  return input;
}
Scott Langham
  • 58,735
  • 39
  • 131
  • 204
1

Similar to the functions overload solution, in python:

def f(number):
 if type(number) != type([]):
  return [].append(number)
 else:
  return -1*number[0]

Alternative: static datamembers

Jordi Kroon
  • 2,607
  • 3
  • 31
  • 55
Markus
  • 1
  • 1
1

Python 2.6:

f = lambda n: (n % 2 * n or -n) + (n > 0) - (n < 0)

I realize this adds nothing to the discussion, but I can't resist.

recursive
  • 83,943
  • 34
  • 151
  • 241
1
int f(int n)
{
   static int x = 0;
   result = -x;
   x = n;
   return result;
}

This is a one entry FIFO with negation. Of course it doesn't work for the max negative number.

phkahler
  • 5,687
  • 1
  • 23
  • 31
1

In Python

f=lambda n:n[0]if type(n)is list else[-n]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
1

Great question!

This took me about 35 secs to think about and write:

int f(int n){
    static int originalN=0;
    if (n!=0)
        originalN=n;
    return n-originalN;
}
Cam
  • 14,930
  • 16
  • 77
  • 128
  • Definitely cheating... but definitely works for all values of `n`, and is simple. x) At first I thought it would only work the first time you called `f(f(n))` (because of the static initialization), but it actually works for each successive time as well. +1 – Tim Leaf May 05 '10 at 16:56
  • Thanks :) Essentially the idea with this answer is that it's a cheeky response to an equally cheeky question. Should one really going hire (or not hire) computer scientists/software engineers based on a question like this? – Cam May 09 '10 at 00:37
1

Scala :

def f(x: Any): Any = x match {
  case i: Int => new { override def hashCode = -i }
  case i @ _  => i.hashCode
}

Same thing in Java :

public static Object f(final Object x) {
  if(x instanceof Integer) {
    return new Object() {
      @Override 
      public int hashCode() {
        return -(Integer)x;
      }
    };
  }
  return x.hashCode();
}
missingfaktor
  • 90,905
  • 62
  • 285
  • 365
1

Another Javascript solution utilizing short-circuits.

​function f(n) {return n.inv || {inv:-n}}

f(f(1)) => -1
f(f(-1)) => 1
Anurag
  • 140,337
  • 36
  • 221
  • 257
1

Thought I'd try this one without looking at other people's answers first:

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

int f(int n) {
    if(n > 0) {  
        if(n % 2)
            return -(++n);
        else {
            return (--n);

        }
    }
    else {
        if(n % 2)
            return -(--n);
        else {
            return (++n);

        }
    }
}

int main(int argc, char* argv[]) {
    int n;
    for(n = INT_MIN; n < INT_MAX; n++) {
        int N = f(f(n));

        if(N != -n) {
            fprintf(stderr, "FAIL! %i != %i\n", N, -n);
        }
    }
    n = INT_MAX;
    int N = f(f(n));
    if(N != -n) {
        fprintf(stderr, "FAIL! n = %i\n", n);
    }
    return 0;
}

Output: [nothing]

Kobi
  • 135,331
  • 41
  • 252
  • 292
Anthony
  • 12,177
  • 9
  • 69
  • 105
1

Doesn't fail on MIN_INT:

int f(n) { return n < 0 ? -abs(n + 1) : -(abs(n) + 1); }
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
1

The problem as stated doesn't require that the function must ONLY accept 32 bit ints, only that n, as given, is a 32-bit int.

Ruby:

def f( n )
  return 0 unless n != 0 
  ( n == n.to_i ) ? 1.0 / n : -(n**-1).to_i
end
Matt Rogish
  • 24,435
  • 11
  • 76
  • 92
1

This will work in a very broad range of numbers:

    static int f(int n)
    {
        int lastBit = int.MaxValue;
        lastBit++;
        int secondLastBit = lastBit >> 1;
        int tuple = lastBit | secondLastBit;
        if ((n & tuple) == tuple)
            return n + lastBit;
        if ((n & tuple) == 0)
            return n + lastBit;
        return -(n + lastBit);
    }

My initial approach was to use the last bit as a check bit to know where we'd be in the first or the second call. Basically, I'd place this bit to 1 after the first call to signal the second call the first had already passed. But, this approach was defeated by negative numbers whose last bit already arrives at 1 during the first call.

The same theory applies to the second last bit for most negative numbers. But, what usually happens is that most of the times, the last and second last bits are the same. Either they are both 1 for negative numbers or they are both 0 for positive numbers.

So my final approach is to check whether they are either both 1 or both 0, meaning that for most cases this is the first call. If the last bit is different from the second last bit, then I assume we are at the second call, and simply re-invert the last bit. Obviously this doesn't work for very big numbers that use those two last bits. But, once again, it works for a very wide range of numbers.

Rui Craveiro
  • 2,224
  • 16
  • 28
1

Seems easy enough.

<script type="text/javascript">
function f(n){
    if (typeof n === "string") {
        return parseInt(n, 10)
    }
    return (-n).toString(10);
}

alert(f(f(1)));
</script>
Kristof Neirynck
  • 3,934
  • 1
  • 33
  • 47
1

Perhaps cheating? (python)

def f(n):    
    if isinstance(n, list):
        return -n[0]
    else:
        return [n,0]    
n = 4
print f(f(n))

--output--
-4
nilamo
  • 1,932
  • 13
  • 22
1

easy:

function f($n) {
   if ($n%2 == 0) return ($n+1)*-1;
   else return ($n-1);
}
  • f(f(8)) => 8%2 == 0 is true => (8+1)*-1 = 9 * -1 = -9. => -9 -1 = -10. That looks pretty wrong (but simple, at least). – user unknown May 30 '11 at 04:33
1

In C,

int 
f(int n) {
     static int r = 0;
     if (r == 1) {r--; return -1 * n; };
     r++;
     return n;
}

It would have helped to know what language this was for. Am I missing something? Many "solutions" seem overly complex, and quite frankly, don't work (as I read the problem).

xcramps
  • 191
  • 1
  • 2
  • It's a valid solution, but as I mentioned on another post it depends on how they want to define function (a true function isn't stateful, it has exactly one return value for any given input value). It's also of value to watch how you feel about implementing state in such a function (it should make you feel queasy and you should naturally try to avoid it until it was the only solution possible IMO) – Bill K Aug 28 '09 at 21:43
1

Here's a C implementation of rossfabricant's answer. Note that since I stick with 32-bit integers at all times, f( f( 2147483647 ) ) == 2147483647, not -2147483647.

int32_t f( int32_t n )
{
    if( n == 0 ) return 0;
    switch( n & 0x80000001 ) {
        case 0x00000000:
            return -1 * ( n - 1 );
        case 0x00000001:
            return n + 1;
        case 0x80000000:
            return -1 * ( n + 1 );
        default:
            return n - 1;
    }
}

If you define the problem to allow f() to accept and return int64_t, then 2147483647 is covered. Of course, the literals used in the switch statement would have to be changed.

splicer
  • 5,344
  • 4
  • 42
  • 47
1

how about this (C language):

int f(int n)
{
    static int t = 1;
    return (t = t ? 0 : 1) ? -n : n;
}

just tried it, and

f(f(1000)) 

returns -1000

f(f(-1000)) 

returns 1000

is that correct or am i missing the point?

Xander
  • 1
  • 1
  • 1
1

Really, these questions are more about seeing the interviewer wrestle with the spec, and the design, error handling, boundary cases and the choice of suitable environment for the solution, etc, more than they are about the actual solution. However: :)

The function here is written around the closed 4 cycle idea. If the function f is only permitted to land only on signed 32bit integers, then the various solutions above will all work except for three of the input range numbers as others have pointed out. minint will never satisfy the functional equation, so we'll raise an exception if that is an input.

Here I am permitting my Python function to operate on and return either tuples or integers. The task spec admits this, it only specifies that two applications of the function should return an object equal to the original object if it is an int32. (I would be asking for more detail about the spec.)

This allows my orbits to be nice and symmetrical, and to cover all of the input integers (except minint). I originally envisaged the cycle to visit half integer values, but I didn't want to get tangled up with rounding errors. Hence the tuple representation. Which is a way of sneaking complex rotations in as tuples, without using the complex arithmetic machinery.

Note that no state needs to be preserved between invocations, but the caller does need to allow the return value to be either a tuple or an int.

def f(x) :
  if isinstance(x, tuple) :
      # return a number.
      if x[0] != 0 :
        raise ValueError  # make sure the tuple is well formed.
      else :
        return ( -x[1] )

  elif isinstance(x, int ) :
    if x == int(-2**31 ):
      # This value won't satisfy the functional relation in
      # signed 2s complement 32 bit integers.
      raise ValueError
    else :
      # send this integer to a tuple (representing ix)
      return( (0,x) )
  else :
    # not an int or a tuple
    raise TypeError

So applying f to 37 twice gives -37, and vice versa:

>>> x = 37
>>> x = f(x)
>>> x
(0, 37)
>>> x = f(x)
>>> x
-37
>>> x = f(x)
>>> x
(0, -37)
>>> x = f(x)
>>> x
37

Applying f twice to zero gives zero:

>>> x=0
>>> x = f(x)
>>> x
(0, 0)
>>> x = f(x)
>>> x
0

And we handle the one case for which the problem has no solution (in int32):

>>> x = int( -2**31 )
>>> x = f(x)

Traceback (most recent call last):
  File "<pyshell#110>", line 1, in <module>
    x = f(x)
  File "<pyshell#33>", line 13, in f
    raise ValueError
ValueError

If you think the function breaks the "no complex arithmetic" rule by mimicking the 90 degree rotations of multiplying by i, we can change that by distorting the rotations. Here the tuples represent half integers, not complex numbers. If you trace the orbits on a number line, you will get nonintersecting loops that satisfy the given functional relation.

f2: n -> (2 abs(n) +1, 2 sign( n) ) if n is int32, and not minint.
f2: (x, y) -> sign(y) * (x-1) /2  (provided y is \pm 2 and x is not more than 2maxint+1

Exercise: implement this f2 by modifying f. And there are other solutions, e.g. have the intermediate landing points be rational numbers other than half integers. There's a fraction module that might prove useful. You'll need a sign function.

This exercise has really nailed for me the delights of a dynamically typed language. I can't see a solution like this in C.

Andrej Panjkov
  • 1,448
  • 2
  • 13
  • 17
1

A C function:

int f(int n) /* Treats numbers in the range 0XC0000000 to 0X3FFFFFFF as valid to
                generate f(f(x)) equal to -x. If n is within this range, it will
                project n outside the range. If n is outside the range, it will
                return the opposite of the number whose image is n. */
{
    return n ? n > 0 ? n <= 0X3FFFFFFF ? 0X3FFFFFFF + n : 0X3FFFFFFF - n :\
           n >= 0XC0000000 ? 0XC0000000 + n : 0XC0000000 - n : 0;
}

Ideone Link for Testing and Download

Apshir
  • 193
  • 8
1

This one's in Python. Works for all negative values of n:

f = abs
pi.
  • 21,112
  • 8
  • 38
  • 59
  • Maybe if it would have been in Haskell instead of Python, half of it wouldn't be a bug. (*Pun: You write it exactly the same in Haskell.*) – comonad Jul 09 '11 at 16:17
1

Here's a variant I haven't seen people use. Since this is ruby, the 32-bit integer stuff sort of goes out the window (checks for that can of course be added).

def f(n)
    case n
    when Integer
        proc { n * -1 }
    when Proc
        n.call
    else
        raise "Invalid input #{n.class} #{n.inspect}"
    end
end

(-10..10).each { |num|
    puts "#{num}: #{f(f(num))}"
}
tommym
  • 2,230
  • 15
  • 11
1

One way to create many solutions is to notice that if we have a partition of the integers into two sets S and R s.t -S=S, -R=R, and a function g s.t g(R) = S

then we can create f as follows:

if x is in R then f(x) = g(x)

if x is in S then f(x) = -invg(x)

where invg(g(x))=x so invg is the inverse function for g.

The first solution mentioned above is the partition R=even numbers, R= odd numbers, g(x)=x+1.

We could take any two infinite sets T,P s.t T+U= the set of integers and take S=T+(-T), R=U+(-U).

Then -S=S and -R=R by their definitions and we can take g to be any 1-1 correspondence from S to R, which must exist since both sets are infinite and countable, will work.

So this will give us many solutions however not all of course could be programmed as they would not be finitely defined.

An example of one that can be is:

R= numbers divisible by 3 and S= numbers not divisible by 3.

Then we take g(6r) = 3r+1, g(6r+3) = 3r+2.

Ivan
  • 191
  • 1
  • 6
1

Easy, just make f return something that appears to equal any integer, and is convertable from an integer.

public class Agreeable
{
    public static bool operator==(Agreeable c, int n)
        { return true; }

    public static bool operator!=(Agreeable c, int n)
        { return false; }

    public static implicit operator Agreeable(int n)
        { return new Agreeable(); }
}

class Program
{
    public static Agreeable f(Agreeable c)
        { return c; }

    static void Main(string[] args)
    {
        Debug.Assert(f(f(0)) == 0);
        Debug.Assert(f(f(5)) == -5);
        Debug.Assert(f(f(-5)) == 5);
        Debug.Assert(f(f(int.MaxValue)) == -int.MaxValue);
    }
}
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
1
const unsigned long Magic = 0x8000000;

unsigned long f(unsigned long n)
{    
    if(n > Magic )
    {
        return Magic - n;
    }

    return n + Magic;
} 

0~2^31

1
int j = 0;

void int f(int n)
{    
    j++;

    if(j==2)
    {
       j = 0;
       return -n;
    }

    return n;
}

:D

Steven
  • 13,501
  • 27
  • 102
  • 146
Omu
  • 69,856
  • 92
  • 277
  • 407
1

What about following:

int f (int n)
{
    static bool pass = false;
    pass = !pass;
    return pass? n : -n;
}
boko
  • 21
  • 1
1

This will work for the range -1073741823 to 1073741822:

int F(int n)
{
    if(n < 0)
    {
        if(n > -1073741824)
            n = -1073741824 + n;
        else n = -(n + 1073741824);
    }
    else
    {
        if(n < 1073741823)
            n = 1073741823 + n;
        else n = -(n - 1073741823);
    }
    return n;
}

It works by taking the available range of a 32 bit signed int and dividing it in two. The first iteration of the function places n outside of that range by itself. The second iteration checks if it is outside this range - if so then it puts it back within the range but makes it negative.

It is effectively a way of keeping an extra "bit" of info about the value n.

joshcomley
  • 28,099
  • 24
  • 107
  • 147
  • p.s. no global variables, and has the advantage of being a simple enough implementation that it can work in a large number of languages – joshcomley May 30 '09 at 15:35
1
void f(int x)
{
     Console.WriteLine(string.Format("f(f({0})) == -{0}",x));
}

Sorry guys... it was too tempting ;)

sebagomez
  • 9,501
  • 7
  • 51
  • 89
1

C++ solution;

long long f(int n){return static_cast <long long> (n);}
int f(long long n){return -static_cast <int> (n);}

int n = 777;
assert(f(f(n)) == -n);
Viktor Sehr
  • 12,825
  • 5
  • 58
  • 90
1

Another cheating solution. We use a language that allows operator overloading. Then we have f(x) return something that has overloaded == to always return true. This seems compatible with the problem description, but obviously goes against the spirit of the puzzle.

Ruby example:

class Cheat
  def ==(n)
     true
  end
end

def f(n)
  Cheat.new
end

Which gives us:

>> f(f(1)) == -1
=> true

but also (not too surprising)

>> f(f(1)) == "hello world"
=> true
waxwing
  • 18,547
  • 8
  • 66
  • 82
1
int f(const int n)  {
    static int last_n;

    if (n == 0)
        return 0;
    else if (n == last_n)
        return -n;
    else
    {
        last_n = n;
        return n;
    }
}

Hackish, but correct.

sth
  • 222,467
  • 53
  • 283
  • 367
0
int f(int n)
{
  static long counter=0;
  counter++;
  if(counter%2==0)
    return -n;
  else
    return n;
}
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
rplusg
  • 3,418
  • 6
  • 34
  • 49
0

a simple solution in f# (not using "tricks")

let rec f n =
    if n = 0 then 0
    elif n > 0 then
        if (f (n - 1) <> n) then n + 1
        else -(n - 1)
    else
        if (f (-(n - 1)) = n) then n - 1
        else -(n + 1) 
Tajomaru
  • 115
  • 1
  • 10
D.F.F
  • 914
  • 1
  • 6
  • 17
0

A Solution in SQL Server

create function dbo.fn_fo(@num int) -- OUTER FUNCTION
RETURNS int
AS
begin
RETURN @num * -1
end
GO

create function dbo.fn_fi(@num int) -- INNER FUNCTION
RETURNS int
AS
begin
RETURN @num * -1
end
GO

declare @num AS int = -42
SELECT dbo.fn_fo(dbo.fn_fi(@num)) -- Gives (-42)
Vishwanath Dalvi
  • 35,388
  • 41
  • 123
  • 155
0

perhaps I'm missing something?

Is this not something as simple as:

    function f(n)
    {
        if(n ==0 || n < 0){return n;}
        return n * -1;
    }

Edit:

so I have miss read the question, ho-hum, so:

    function f(n)
    {
        if(!c(n,"z")&&!c(n,"n")){if(n==0){return "z"+n;}return "n"+n;}
        if( c(n,"z")){return 0;}return parseInt(n.replace("n",""))*-1;
    }
    function c(x,y){return x.indexOf(y) !==-1;}

ugly but works.

Darknight
  • 2,460
  • 2
  • 22
  • 26
0

f(x) = the point (x) rotated 90 degrees counterclockwise around the origin in a 2D Cartesian coordinate system. Inputs of only one number x are presumed to be (x, 0), and outputs having y=0 are provided as the single number x.

object f: (object) x {
    if (x.length == 1)
        x = (x, 0)
    swap = x[0]
    x[1] = x[0]
    x[0] = -swap
    if (x[1] == 0)
        x = x[0]
    return x
David Stein
  • 866
  • 7
  • 21
  • Which programming language is it? – The Mask Jun 25 '13 at 16:02
  • "Where n is a 32 bit **signed integer**; you can't use complex numbers arithmetic." – Zecc Jun 25 '13 at 16:05
  • @Mask: It's pseudocode. Can easily be translated into any language. – David Stein Jun 25 '13 at 19:51
  • @Zecc: I don't think that you understand the concept of "complex numbers arithmetic." The code that I posted does not use complex math in the mathematical sense - nor in the colloquial sense: it is trivially simple to understand and apply. – David Stein Jun 25 '13 at 19:52
  • @DavidStein Yes, I know. I quoted too much and commented too less, and I apologize for that. What I meant is that `x` should be a 32 bit signed integer. Now I realize that's why you start with the test for `x.length == 1`. The pseudocode threw me off. – Zecc Jun 26 '13 at 07:37
0

I confess that I'd cheat, but meet the requirements nevertheless. This is programming wizardry, not really Mathematics. It works for the whole range, except -2^31.

int f(int n)
{
    static bool eFlag = false; // Only executed once
    eFlag = !eFlag;
    return eFlag?-n:n;
}
Hameer Abbasi
  • 1,292
  • 1
  • 12
  • 34
0

Another cheating solution in C++, operator overloading.

struct func {
    int n;
    func operator()(int k) { n = -k; return *this; }
    int operator()(const func &inst) { return inst.n; }
} f;
skies457
  • 116
  • 6
0

Objective-C

This works for all numbers except "-1".

If you are to go from using int to using NSInt then you can set -1 values to NULL and then convert them the second time to +1, but I feel that NSInt cheats what the asker intended.


f(n):

-(int)f:(int)n {
    if (abs(n)==1) {
        n = -1;
    } else {
        if (abs(n)%2) {//o
            if (n>0) {//+
                n--;
                n*=+1;
            } else if (n<0) {//-
                n++;
                n*=+1;
            }
        } else {//e
            if (n>0) {//+
                n++;
                n*=-1;
            } else if (n<0) {//-
                n--;
                n*=-1;
            }
        }
    }
    return n;
}

Of course this could all be shortened down to like one line, but then other people might not be able to read along...


Anyways, I stored the BOOLEAN logic in the state of the number being either odd or even.

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195
0

I believe this meets all the requirements. Nothing says that the parameters have to be 32 bit signed integers, only that the value 'n' you pass in is.

long long f(long long n)
{
    int high_int = n >> 32;
    int low_int  = n & 0xFFFFFFFF;

    if (high_int == 0) {
        return 0x100000000LL + low_int;
    } else {
        return -low_int;
    }
}
jcoder
  • 29,554
  • 19
  • 87
  • 130
0

F#

let f n =
    match n with
    | n when n % 2 = 0 -> -n + System.Math.Sign n
    | _ -> n - System.Math.Sign -n

where n such that System.Int32.MinValue < n < System.Int32.MaxValue.

Tajomaru
  • 115
  • 1
  • 10
0

I tried golfing this answer by Rodrick Chapman.

Without branches: 74 chars

int f(int i){return(-((i&1)<<1)|1)*i-(-((i>>>31)<<1)|1)*(((i|-i)>>31)&1);}

With branches, Java style: 58 chars

int f(int i){return i==0?0:(((i&1)==0?i:-i)+(i>0?-1:1));}

With branches, C style: 52 chars

int f(int i){return i?(((i&1)?-i:i)+(i>0?-1:1)):0;}

After a quick, but valid, benchmark, the branched version turns out to be 33% faster on my machine. (Random dataset of positive and negative numbers, enough repetition and prevented the compiler to optimize out the code, with warmup.) This is not so surprising, given the number of operations in the unbranched version and the possible good branch prediction because of the fact that the function is called twice: f(f(i)). When I change the benchmark to measure: f(i), the branched version is only 28% faster. I think this proves that the branch prediction actually did some good in the first case. More prove: when testing with f(f(f(f(i)))), it turns out the branched version is 42% faster.

Community
  • 1
  • 1
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
0

Solution in the Wolfram Language:

f[f[n_]] := -n

Application:

In[2]:= f[f[10]]                                                                                                                                                                                                                                                                              
Out[2]= -10
In[3]:= f[10]                                                                                                                                                                                                                                                                                 
Out[3]= f[10]

Because the question does not say anything the value of f(n), f[n] remains unevaluated.

sakra
  • 62,199
  • 16
  • 168
  • 151
0

C# overloading:

string f(int i) {
  return i.ToString();
}

int f(string s) {
  return Int32.Parse(s) * -1;
}

Or

object f(object o) {
  if (o.ToString.StartsWith("s"))
    return Int32.Parse(s.Substring(1)) * -1;
  return "s" + i.ToString();
}
Dinah
  • 52,922
  • 30
  • 133
  • 149
0

Tcl:

proc f {input} {
    if { [string is integer $input] } {
      return [list expr [list 0 - $input]]
    } else {
      return [eval $input]
    }
}

% f [f 1]
-1

Along the lines of some of the other answers... if it's an integer, return a command that returns the negative of that number. If it's not a number, evaluate it and return the result.

RHSeeger
  • 16,034
  • 7
  • 51
  • 41
0

This is a C/C++ solution that doesn't utilize any bitwise operators, and doesn't require any math libraries, though it's kind of cheating...

double f(double n)
{
    if (n == (double)(int)n)
        return n + 0.5;
    else
        return -(n - 0.5);
}

This works for all 32-bit integers with the single exception of 0x80000000 (since its opposite cannot be stored in the 32-bit integer system). f(f(n)) == -n will always be true except in that one case.

I'm sure there's a simpler and faster way to implement it, though. This was just the first thing that came to mind.

Tim Leaf
  • 388
  • 3
  • 15
0

Javascript

function f(n)  { 
        return typeof n === "number" ? 
        function() {return -n} : 
        n();
}
ssh
  • 195
  • 1
  • 11
0

Based on the questions that Microsoft/Google's interviewers usually ask in their interviews, I believe the asker means an innovative, lightweight, simple solution that will use bitwise operations, not those complicated high level answers.

Inspired by the answer of @eipipuz, I wrote this C++ function (yet didn't run it):

int32_t f(int32_t n){
    int32_t temp = n & 00111111111111111111111111111111;
    x = n >> 30;
    x++;
    x = x << 30;
    return x | temp;
}

It stores the leftmost two bits of n in x, adds 1 to x, and then replaces it as the leftmost two bits of n again.

If we keep running f(n) with another f(n) as the parameter n, the leftmost two bits will rotate like this:

00 --> 01 --> 10 --> 11 --> 00 ...

Note that the rightmost 30 bits don't change. Examples for 8 bit integers:

Example 1:

  • > f(00001111) = 01001111
  • > f(01001111) = 10001111 [this is negative of the original value, 00001111]

Example 2:

  • > f(11101010) = 00101010
  • > f(00101010) = 01101010 [this is negative of the original value, 11101010]
Alisa
  • 2,892
  • 3
  • 31
  • 44
0
int func(int a)  
{   
    static int p = 0;  
    int ret = a;  

    if ( p ) ret *= -1;  
    p ^= 1;  

    return ret;  
}  
Artur
  • 7,038
  • 2
  • 25
  • 39
0

I don't know if this is completely right, but wouldn't a simple flag work? In C, using a static local variable, I successfully did this:

int main()
{
    int n = -256; // 32-bit signed integer
    printf("%d", f(f(n)));
}

int f(int n){
    static int x = 0; // not returning negative;
    switch(x){
        case 0:
            x = 1;
            return n;
            break;

        case 1:
            x = 0;
            return -n;
            break;
        default:
            return -999;
            break;
    }
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Eudis Duran
  • 742
  • 3
  • 16
0
#include <cmath>

int f(int n)
{
    static int count = 0;
    return ::cos(M_PI * count++) * n;
}
0

In awk, since there's hardly any information being passed down, one has to resort to methods that allows state information being passed as part of the function return, without jeopardizing the usability of what's being passed down :

jot - -5 5 | mawk 'function _(__,___) { 

     return (__~(___=" ")) \
      \
      ? substr("",sub("^[ ]?[+- ]*",\
        substr(" -",__~__,index("_"___,___)-\
              (__~"[-]")),__))\
            (__~"[-]"?"":___)__\
      : (+__<-__?___:(___)___)__ 

  } BEGIN { CONVFMT=OFMT="%.17g" 
  } { 
      print "orig",           +(__=$(__<__))<-__?__:" "__,
            "f(n)....",        _(__),_(_(__)),_(_(_(__))),
                         _(_(_(_(__)))), _(_(_(_(_(__))))) 

  }' |gcat -n | lgp3 5 

 1  orig -5 f(n)....  -5   5  -5   5  -5
 2  orig -4 f(n)....  -4   4  -4   4  -4
 3  orig -3 f(n)....  -3   3  -3   3  -3
 4  orig -2 f(n)....  -2   2  -2   2  -2
 5  orig -1 f(n)....  -1   1  -1   1  -1

 6  orig  0 f(n)....   0  -0   0  -0   0
 7  orig  1 f(n)....   1  -1   1  -1   1
 8  orig  2 f(n)....   2  -2   2  -2   2
 9  orig  3 f(n)....   3  -3   3  -3   3
10  orig  4 f(n)....   4  -4   4  -4   4

11  orig  5 f(n)....   5  -5   5  -5   5

So the limit of this is that only integers or floating point values already in a string format that can be used without risking , since an extra ASCII space \040 is prepended as state information

The upside of this method is that

  1. it's willing to provide you with "negative-zero",

  2. for integers less than 2^53 in absolute value, simply adding a plus sign,

    i.e. +f(f(_))

    to the function call itself would have implicit type-casting done on your behalf, and the resulting value will once again be numeric

    for Big Integers, just substr() out any leading spaces

  3. handle bigintegers with ease without risking loss of precision from being type-casted to a double-precision float

`

    1   orig -99999999999999999999999999999999 
        f(n).... 
             -99999999999999999999999999999999   
              99999999999999999999999999999999
             -99999999999999999999999999999999   
              99999999999999999999999999999999  
             -99999999999999999999999999999999

 2  orig      -1239999999999999999999999999999 
    f(n)....  -1239999999999999999999999999999                   
               1239999999999999999999999999999
              -1239999999999999999999999999999
               1239999999999999999999999999999
              -1239999999999999999999999999999`
RARE Kpop Manifesto
  • 2,453
  • 3
  • 11
0

I'm late to this party and it's probably a graveyard now. But I have 2 contributions, inspired by viraptor's previous Python answer using lambda. A reader might think that solution is only viable in an untyped language, and that in a typed language it would require some explicit extra tagging.

But below is solution 1 in Haskell (I'm not a Haskell expert). It cheats a little, because technically, the two f's are two different implementations. (one f :: Int -> () -> Int, and the other f :: (() -> Int) -> Int)

{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FunctionalDependencies #-}

module Main where

class Tran σ τ | σ -> τ where
  tran :: σ -> τ

instance Tran Int (() -> Int) where
  tran n = \_ -> (-n)

instance Tran (() -> Int) Int where
  tran g = g ()

f :: Tran σ τ => σ -> τ
f = tran

main :: IO ()
main = do
  print $ f (f (42 :: Int)) -- --> -42
  print $ f (f (0 :: Int)) -- --> 0
  print $ f (f (-69 :: Int)) -- --> 69

Next is solution 2 in Typed Racket. This one satisfies the property for the largest domain possible, because Number in Racket includes up to complex numbers:

#lang typed/racket

(: f (case->
      [Number -> (-> Number)]
      [(-> Number) -> Number]))
(define (f x)
  (if (number? x) (λ () (- x)) (x)))

(f (f 42))    ; --> -42
(f (f 0))     ; --> 0
(f (f -69))   ; --> 69
(f (f 3/4))   ; --> -3/4
(f (f 8+7i))  ; --> -8-7i
Phil
  • 5,595
  • 5
  • 35
  • 55
0

This idea's been used in other answers, but I got it into one line of Python:

def f(n):
    return str(n) if type(n) == int else -int(n)
user240515
  • 3,056
  • 1
  • 27
  • 34
-1

using a cyclic permutation method to do this.

-b a b -a

a b -a -b

in the trivial situation f(0) returns 0

sorry for my rough answer by my phone, after 28th i will post a full version (now examing... ) briefly saying, think f(n) is a cyclic permutation,the questions is how to construct it.

define fk = f(f(f(f(...f(n))))) (k fs) situation k=2 0.trivial situation f(0) returns 0 1. make groups , in situation k=2, groups: {0} {1,2} {3,4} ... {n,n+1 | (n+1)%2 = 0 } ,attention: I ONLY use Z+, because the construction doesnt need use negative number. 2.construct permutation : if n % 2 = 0, so a=n-1 b=n if n % 2 = 1, so a=n b=n+1

this will generate the same permutation, because n and f(n) are in the same group.

note the permutation as P return P(n)

for k=2t , only doing the same things above, just MOD k. for k=2t-1, although the method works, but it makes no sense, ahh? (f(n) = -n is ok)

Latyas
  • 35
  • 6
-1

it's cheating by saving state but it works, break operation into two: -n = (~n + 1) for integers

int f(int n) {
    static int a = 1;
    a = !a;
    if (a) {
        return (~n);
    } else {
        return (n+1);
    }
}
wobmene
  • 1,108
  • 9
  • 14
-1

I thought the largest range possible was hinting at a modular arithmetic solution. In some modular bases M there is number which when squared is congruent to M-1 (which is congruent to -1). For example if M=13, 5*5=25, 25 mod 13=12 (= -1)
Anyway here's some python code for M=2**32-3.

def f(x):
    m=2**32-3;
    halfm=m//2;
    i_mod_m=1849436465
    if abs( x ) >halfm:
        raise "too big"
    if x<0:
        x+=m
    x=(i_mod_m*x) % m
    if (x>halfm):
        x-=m
    return x;

Note there are 3 values it wont work for 2 ** 31-1, -(2 ** 31-1) and -(2 ** 31)

sth
  • 222,467
  • 53
  • 283
  • 367
paperhorse
  • 4,095
  • 2
  • 22
  • 12
-1
int f(int x){
    if (x < 0)
        return x;
    return ~x+1; //two's complement
}
Alex
  • 4,316
  • 2
  • 24
  • 28
-1

PHP, without using a global variable:

function f($num) {
  static $mem;

  $answer = $num-$mem;

  if ($mem == 0) {
    $mem = $num*2;
  } else {
    $mem = 0;
  }

  return $answer;
}

Works with integers, floats AND numeric strings!

just realized this does some unnecessary work, but, whatever

Henrik Paul
  • 66,919
  • 31
  • 85
  • 96
-1

Isn't remembering your last state a good enough answer?

int f (int n)
{
    //if count 
    static int count = 0;

    if (count == 0)
        { 
            count = 1;
            return n;
        }

    if (n == 0)
        return 0;
    else if (n > 0)
    {
        count = 0;
        return abs(n)*(-1);
    } 
    else
    {
        count = 0;
        return abs(n);
    }
}

int main()
{
    int n = 42;
    std::cout << f(f(n))
}
jkeys
  • 3,803
  • 11
  • 39
  • 63
  • Depends on the interviewers definition of "Function". That's a method--a function doesn't really have state. But maybe they didn't mean function that literally. – Bill K Aug 28 '09 at 21:40
  • It's not thread safe and overly complicated for expressing state != state – user unknown May 30 '11 at 04:59
-2

I haven't looked at the other answers yet, I assume the bitwise techniques have been thoroughly discussed.

I thought I'd come up with something evil in C++ that is hopefully not a dupe:

struct ImplicitlyConvertibleToInt
{
    operator int () const { return 0; }
};

int f(const ImplicitlyConvertibleToInt &) { return 0; }

ImplicitlyConvertibleToInt f(int & n)
{
    n = 0; // The problem specification didn't say n was const
    return ImplicitlyConvertibleToInt();
}

The whole ImplicitlyConvertibleToInt type and overload is necessary because temporaries can't be bound to a non-const reference.

Of course, looking at it now it's undefined whether f(n) is executed before -n.

Perhaps a better solution with this degree of evil is simply:

struct ComparesTrueToInt
{
    ComparesTrueToInt(int) { } // implicit construction from int
};
bool operator == (ComparesTrueToInt, int) const { return true; }

ComparesTrueToInt f(ComparesTrueToInt ct) { return ComparesTrueToInt(); }
Marsh Ray
  • 2,827
  • 21
  • 20
  • C++ gets a bad rep because of people like you. This is a horrible practice... and while it somewhat solves the comparison `f(f(x)) == -x`, it's completely useless and destructive for any other use. You're right that it is evil; but that is not in any way a good thing. Besides... what are you going to do if someone tests your function like this: `cout << x << (f(f(x)) == -x ? " works." : " doesn't work.") << endl;` The result is undefined. In my version of GCC it prints zero every line. Caught red-handed! – Tim Leaf May 06 '10 at 13:30
-2

In Less than 50 characters (C#)

int f(int n) { return (n <= 0) ? n : f(-n); }

Or easier to read:

static int f(int n) { 
  if (n <= 0)
    return n;
  else 
    return f(-n);
}

To Test

static void Main(string[] args) {
    for (int n = int.MinValue; n < int.MaxValue; n+=1) {
        Console.Out.WriteLine("Value: " + n + " Result: " + f(f(n)));
    }
}

And it works ( assuming I understand the question properly )

Armstrongest
  • 15,181
  • 13
  • 67
  • 106
  • That only works when `n` is initially positive (or zero). The question clearly states `Where n is a 32 bit *signed integer*`, meaning n can also start out negative. – Tim Leaf May 05 '10 at 16:48
-4

How about

int f(int n)
{
    return -abs(n);
}
Alex
  • 601
  • 5
  • 5