79

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
zippy
  • 981
  • 1
  • 6
  • 8
  • 4
    Related: http://stackoverflow.com/questions/1348080/convert-a-positive-number-to-negative-in-c-sharp and http://stackoverflow.com/questions/5213338/fastest-way-to-flip-the-sign-of-a-double-float-in-c and http://stackoverflow.com/questions/4866187/how-to-flip-the-sign-of-an-integer-value-using-some-constant-and-operators-wit – Shog9 Oct 24 '11 at 17:12
  • int x = 5; x = -x; – NomadMaker Apr 05 '20 at 23:22

13 Answers13

281

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

FailedDev
  • 26,680
  • 9
  • 53
  • 73
  • 3
    @pst No it won't. At least not with JDK 1.6.0_11 ;D – Gandalf Oct 24 '11 at 12:31
  • 14
    For me the wrong answer has been accepted. It is a valid answer, but given that the OP is asking to change sign of an int, so there is no concern about negative zero or other concepts, I would suggest x = -x is more expressive (see EJP's answer below)... – drrob Aug 17 '15 at 12:29
  • 1
    Addendum to previous comment: see also Bohemian's answer as it explains the unary operator in more detail – drrob Aug 17 '15 at 14:24
  • @drrob You do realize that any decent compiler will anyway use x = -x right? – FailedDev Aug 17 '15 at 22:56
  • 1
    @FailedDev sure, but I said it is more expressive (not better for performance) – drrob Aug 18 '15 at 10:33
  • 3
    this answer is not correct. int has the minimum value of -2^31 and a maximum value of 2^31-1 which means that in the particular case when you need to convert Integer.MIN_VALUE this will NOT work and also will not throw an exception (what I think it is really bad) – vinicius.hisao Mar 23 '20 at 12:19
115
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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 8
    This does not work in the case where x = Integer.MIN_VALUE and will silently fail*. To be safe, you should check for this case and throw an exception, or use the library function negateExact, which does exactly that. – rdllopes Mar 14 '16 at 13:06
  • 4
    @rdllopes The same applies to practically every answer here. – user207421 Mar 15 '16 at 00:18
  • Note though that it won't compile if x is short or byte, whereas `x *= -1` will. Was a bit surprised when I discovered that which is how I came across this page :) Of course you can cast, but I was auto-generating code where x could be byte, short, int or long... – Dave Griffiths Feb 14 '17 at 10:34
  • @DaveGriffiths You were autogenerating code to change the sign of a variable? – user207421 Feb 26 '17 at 23:26
  • Yeah - parsing something where the sign appears after the number :) – Dave Griffiths Feb 28 '17 at 08:07
  • @rdllopes In fact it applies to every possible answer. When `x == `Integer.MIN_VALUE` *there is no solution.* – user207421 Aug 25 '21 at 10:20
  • Well, I provided the safe solution. Now, noticed that I just gave a comment for one corner case. As programmers we should have that in mind if the problem might fall in that case. Otherwise, your solution is really good. – rdllopes Aug 25 '21 at 15:26
  • And if the value is already negative and he wants to convert it to positive? Then your answer fails. – Black Jun 16 '22 at 14:58
56

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
11

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

user207421
  • 305,947
  • 44
  • 307
  • 483
Shivanshu Goyal
  • 1,374
  • 2
  • 16
  • 22
  • 7
    In reality don't do this, just do `x = -x`. From an assembly perspective, `-x` is a simple `neg` instruction while `~x` and `++x` requires a `not` and `add` instruction. – vallentin Sep 27 '16 at 01:49
7

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.

Salix alba
  • 7,536
  • 2
  • 32
  • 38
  • 11
    If you want your code to be robust against this corner case, Java 8 provides [Math.negateExact](http://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#negateExact-int-) that will throw an `ArithmeticException` when trying to negate MIN_VALUE, rather than silently returning the wrong result. – Jeffrey Bosboom Sep 15 '14 at 01:04
6

Yes, as was already noted by Jeffrey Bosboom (Sorry Jeffrey, I hadn't noticed your comment when I answered), there is such a function: Math.negateExact.

and

No, you probably shouldn't be using it. Not unless you need a method reference.

Community
  • 1
  • 1
old grouch
  • 81
  • 1
  • 4
5

Necromancing here.
Obviously, x *= -1; is far too simple.

Instead, we could use a trivial binary complement:

number = ~(number - 1) ;

Like this:

import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int iPositive = 15;
        int iNegative = ( ~(iPositive - 1) ) ; // Use extra brackets when using as C preprocessor directive ! ! !...
        System.out.println(iNegative);

        iPositive =  ~(iNegative - 1)  ;
        System.out.println(iPositive);

        iNegative = 0;
        iPositive = ~(iNegative - 1);
        System.out.println(iPositive);


    }
}

That way we can ensure that mediocre programmers don't understand what's going on ;)

Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
5

original *= -1;

Simple line of code, original is any int you want it to be.

K.D. Code
  • 79
  • 1
  • 5
4

The easiest thing to do is 0- the value

for instance if int i = 5;

0-i would give you -5

and if i was -6;

0- i would give you 6

Jebjosh
  • 83
  • 8
1

You can use the minus operator or Math.abs. These work for all negative integers EXCEPT for Integer.MIN_VALUE! If you do 0 - MIN_VALUE the answer is still MIN_VALUE.

lovos
  • 21
  • 3
0

For converting a negative number to positive. Simply use Math.abs() inbuilt function.

int n = -10;
n = Math.abs(n);

All the best!

Aamer
  • 417
  • 3
  • 9
-2

In kotlin you can use unaryPlus and unaryMinus

input = input.unaryPlus()

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html

Emmanuel Loisance
  • 706
  • 1
  • 12
  • 22
-4

You can use Math:

int x = Math.abs(-5);
Thiago Araújo
  • 800
  • 9
  • 8