Java math function to convert positive int to negative and negative to positive?

Is there a Java function to convert a positive int to a negative one and a negative int to a positive one?

I'm looking for a reverse function to perform this conversion:

-5  ->  5
 5  -> -5

Solution 1:

What about x *= -1; ? Do you really want a library function for this?

Solution 2:

x = -x;

This is probably the most trivial question I have ever seen anywhere.

... and why you would call this trivial function 'reverse()' is another mystery.

Solution 3:

Just use the unary minus operator:

int x = 5;
...
x = -x; // Here's the mystery library function - the single character "-"

Java has two minus operators:

  • the familiar arithmetic version (eg 0 - x), and
  • the unary minus operation (used here), which negates the (single) operand

This compiles and works as expected.

Solution 4:

Another method (2's complement):

public int reverse(int x){
    x~=x;
    x++;
    return x;
}

It does a one's complement first (by complementing all the bits) and then adds 1 to x. This method does the job as well.

Note: This method is written in Java, and will be similar to a lot of other languages

Solution 5:

No such function exists or is possible to write.

The problem is the edge case Integer.MIN_VALUE (-2,147,483,648 = 0x80000000) apply each of the three methods above and you get the same value out. This is due to the representation of integers and the maximum possible integer Integer.MAX_VALUE (-2,147,483,647 = 0x7fffffff) which is one less what -Integer.MIN_VALUE should be.