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

后端 未结 13 2120
暗喜
暗喜 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:51

    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.

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

    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.

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

    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.

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

    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

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

    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

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

    We can reverse Java number int or double using this :

    int x = 5;
    int y = -7;
    
    x = x - (x*2); // reverse to negative
    y = y - (y*2); // reverse to positif
    

    Simple algorithm to reverse number :)

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