Converts negative number to positive

-2

Is there any native java library that will help me in an elegant way to convert a negative number to a positive number.

I did not want to do it this way:

public class Main {  

    public static void main(String[] args) {  
        int i1 = 10;  
        int i2 = -i1;  
        int i3 = -i2;  

        System.out.printf("%d\n%d\n%d", i1, i2, i3);  
    }  
}  
    
asked by anonymous 15.07.2014 / 23:44

3 answers

3

The great trick is to use the math module function or absolute value to print the that is desired. Because it is a fairly common function to find it in most programming languages in Java, the same is defined in Math.abs () and abs () is the acronym for absolute in English.

In this way your code could use this way:

public class Main {

    public static void main(String[] args) {
        int i1 = -10;
        //Pega o valor absoluto de i1 isto é o módulo do mesmo
        int i2 = Math.abs(i1);
        System.out.println(i1);
        System.out.println(i2);
    }
}

Another way to do this would be through regular expressions, but it would not make sense to use a regular expression and conversions just to pick up the module from a number since this operation would be very costly ):

public class Main {

    public static void main(String[] args) {
        int i1 = -10;
        String regex = "" + i1;
        regex = regex.replaceAll("[^0-9]", "");
        int i2 = Integer.parseInt(regex);
        System.out.println(i2);
    }
}

Note that it's pretty much the same thing if you do with replace:

regex = regex.replaceAll("-", "");

or

regex = regex.substring(1); //retira o primeiro caractere

Although all of these methods work does not make up for creating a String object only to do a conversion when Java already provides the function in the Math Library.

    
16.07.2014 / 00:44
2

According to the suggestion of @Olimon F. and resolving in just one line

int i2 = -1;
int x = ((i2 < 0) ? -i2 : i2);
System.out.println(x);

// output: 1
    
16.07.2014 / 01:29
-3

Another solution to the problem:

int N = -3
int R = ((N*2)+N)

The result of R is 3.

    
07.09.2017 / 20:52