How can I change the sign of a number?
abs();
will not return me a negative when the input is positive, correct? I need the opposite sign.
How can I change the sign of a number?
abs();
will not return me a negative when the input is positive, correct? I need the opposite sign.
Check out (answer to previous version of question).Math.Abs
Use the negative sign:
var answer = -amount;
in C++, simply abs(x)
which is in math.h
This is the Absolute Value function.
Just multiply by -1:
double d = 1.2345;
double opposite = d * -1;
This is too obvious:
n = -n
You should use:
n = ~--n;
..or, if you like the OR bitwise, use:
n = (0xffffffff ^ n) + 1;
...if that +1 is too obvious for you, this is a sure bet:
n ^= 0xffffffff;
int m;
for (m = 1; m != 0 && ((n & m) != 0); m <<= 1);
n |= m;
if (m == 0) n = m;
else for (m >>= 1; m != 0; n ^= m, m >>=1);
...there's also the option for people who want to make sure none of their processing power goes unused:
public int invert(int n) {
Random r = new Random();
while (true) {
int s = r.nextInt();
if ((s + n) == 0) {
return s;
}
}
}