I have to write a method which converts an int value to the same negative int value. For example, if the user types in 5 the method should give back -5.
The whole story is: The method has a transfer parameter which is either a positive or a negative int. Is it a positive int, we should change it to a negative int. If it is a negative int, do nothing. It is also hard to check if the given int is positive or negative.
The regulations:
+
and all the boolean operations. But in this case I know that I have to use XOR.How can I change a value to its negative value using only XOR and +
?
ATTENTION: The only operations allowed are:
!
^
&&
||
+
No *, no -, no ~
Edit: The two solutions from CherryDT and MikeC are working well. Any ideas how to check if its a negative or a positive parameter with the same regulations? I thought this would be the easy part. Then realized it isn't.
(x ^ -1) + 1
Explanation: Basically, it's the same as ~x + 1
. -1
has all bits set, and therefore inverts all bits when XORed with, just like NOT. And since, the other way round, inverting will always give you -x - 1
, all you need to do is invert and add 1.