Java math function to convert positive int to negative and negative to positive?
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.
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.
What about x *= -1;
? Do you really want a library function for this?
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