Tutorial :Function for flipping the sign of a number



Question:

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.


Solution:1

Just multiply by -1:

double d = 1.2345;  double opposite = d * -1;  


Solution:2

Dude. Minus.

double d = 1.1234;  double opposite = -d;  


Solution:3

Check out Math.Abs (answer to previous version of question).

Use the negative sign:

var answer = -amount;  


Solution:4

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;      }    }  }  


Solution:5

in C++, simply abs(x) which is in math.h
This is the Absolute Value function.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »