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

后端 未结 13 2172
暗喜
暗喜 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条回答
  •  Happy的楠姐
    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 ;)

提交回复
热议问题