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

后端 未结 13 2119
暗喜
暗喜 2020-12-01 04:29

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 perfor

相关标签:
13条回答
  • 2020-12-01 04:40

    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

    0 讨论(0)
  • 2020-12-01 04:42

    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 ;)

    0 讨论(0)
  • 2020-12-01 04:43

    You can use Math:

    int x = Math.abs(-5);
    
    0 讨论(0)
  • 2020-12-01 04:48

    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.

    0 讨论(0)
  • 2020-12-01 04:50

    original *= -1;

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

    0 讨论(0)
  • 2020-12-01 04:51

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

    0 讨论(0)
提交回复
热议问题