Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a negative number positive

Just call Math.abs. For example:

int x = Math.abs(-5);

Which will set x to 5.

Note that if you pass Integer.MIN_VALUE, the same value (still negative) will be returned, as the range of int does not allow the positive equivalent to be represented.


The concept you are describing is called "absolute value", and Java has a function called Math.abs to do it for you. Or you could avoid the function call and do it yourself:

number = (number < 0 ? -number : number);

or

if (number < 0)
    number = -number;

You're looking for absolute value, mate. Math.abs(-5) returns 5...


Use the abs function:

int sum=0;
for(Integer i : container)
  sum+=Math.abs(i);

Try this (the negative in front of the x is valid since it is a unary operator, find more here):

int answer = -x;

With this, you can turn a positive to a negative and a negative to a positive.


However, if you want to only make a negative number positive then try this:

int answer = Math.abs(x);

A little cool math trick! Squaring the number will guarantee a positive value of x^2, and then, taking the square root will get you to the absolute value of x:

int answer = Math.sqrt(Math.pow(x, 2));

Hope it helps! Good Luck!


This code is not safe to be called on positive numbers.

int x = -20
int y = x + (2*(-1*x));
// Therefore y = -20 + (40) = 20

Are you asking about absolute values?

Math.abs(...) is the function you probably want.