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
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.
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.
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:
0 - x
), andThis compiles and works as expected.
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
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
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 :)