Make a negative number positive
I have a Java method in which I'm summing a set of numbers. However, I want any negatives numbers to be treated as positives. So (1)+(2)+(1)+(-1) should equal 5.
I'm sure there is very easy way of doing this - I just don't know how.
Read more... Read less...
You're looking for absolute value, mate.
Math.abs(-5) returns 5...
int sum=0; for(Integer i : container) sum+=Math.abs(i);
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
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);
OR, if you would prefer not to use the abs() method for some reason then try this:
int answer = Math.sqrt(Math.pow(x, 2));
Hope it helps! Good Luck!
Are you asking about absolute values?
Math.abs(...) is the function you probably want.