Sunday, March 27, 2011

Make a negative number positive in Java

Hi, I'm sure this is a very simple question! 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!! Any tips would be much appreciated.

From stackoverflow
  • Just call Math.abs?

    JB King : Jon Skeet gets another one. ;)
    Zach Scrivena : Note the edge cases, e.g. Math.abs(Integer.MIN_VALUE) = Integer.MIN_VALUE.
  • Are you asking about absolute values?

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

  • 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;
    
    Paul Tomblin : Oh, dilemma time - there are so many equally good answers, that I might as well delete mine. But then I'd lose 40 points, and I'll never catch Jon Skeet if I do that.
    cletus : Sorry -1 for reinventing a standard library call.
    Paul Tomblin : @cletus, did you notice that I had already mentioned the standard library call? Or that in this case, the "reinvent" takes fewer instructions that calling the library?
    simon : Also worth understanding the details behind the library call. Especially if there are side effects to the library call, or performance issues like Paul mentions.
  • Use the abs function:

    int sum=0;
    for(Integer i : container)
      sum+=Math.abs(i);
    
  • The easiest, if verbose way to do this is to wrap each number in a Math.abs() call, so you would add:

    Math.abs(1) + Math.abs(2) + Math.abs(1) + Math.abs(-1)
    

    with logic changes to reflect how your code is structured. Verbose, perhaps, but it does what you want.

    Dan Dyer : You could make it less verbose with a static import.
  • You're looking for absolute value, mate. Math.abs(-5) returns 5...

  • You want to wrap each number into Math.abs(). e.g.

    System.out.println(Math.abs(-1));
    

    prints out "1".

    If you want to avoid writing the Math.-part, you can include the Math util statically. Just write

    import static java.lang.Math.abs;
    

    along with your imports, and you can refer to the abs()-function just by writing

    System.out.println(abs(-1));
    
  • 1 more

    Why don't you use:

    Ma..ab....

    ... Oh.

0 comments:

Post a Comment