Addition and subtraction in a chain

5

I need to implement the following:

Entry (a string):

5+45+100-125+5-10

Exit:

= 20

Here the code implemented only for positive numbers:

String operacion="10+200+3000";
    int tam = operacion.length();
    String A[] = new String[100];
    int pos = 0;
    int sum = 0;
    String aux = "";
    for(int i = 0; i<tam ; i++)
    {
        if(operacion.charAt(i) == '+')
        {
            A[pos] = aux;
            pos++;
            aux = "";
        }
        else
        {
            aux = aux + operacion.charAt(i);
        }
    }
    A[pos] = aux;
    pos++;
    for(int i = 0; i<pos ; i++)
    {
        sum=sum+Integer.parseInt(A[i]);
    }
    System.out.println("=  "+sum);

Exit

= 3210

The problem is that I can not do it for the negatives to do the operation.

    
asked by Raul J. 09.12.2016 в 01:36
source

4 answers

2

One option would be to store the operators, and in the last loop, perform the respective operation:

   String operacion="5+45+100-125+5-10";      
   int tam = operacion.length();
    String A[] = new String[100];
    //Array para almacenar operadores.
    String operaciones[] = new String[100];
    int pos = 0;
    int sum = 0;
    String aux = "";

    //inicializa primer operador.
    operaciones[0] = "+";
    int index_operacion = 1;
    for(int i = 0; i<tam ; i++)
    {
        if(operacion.charAt(i) == '+' || operacion.charAt(i) == '-')
        {
            A[pos] = aux;
            operaciones[index_operacion] = String.valueOf(operacion.charAt(i));
            pos++;   
            index_operacion++;
            aux = "";            
        }
        else
        {
            aux = aux + operacion.charAt(i);
        }        
    }
    A[pos] = aux;
    pos++;

    for(int i = 0; i<pos ; i++)
    {           
        //Determina la operación a realizar.         
        if(operaciones[i].equals("+")){
         sum=sum+Integer.parseInt(A[i]);    
        }else if (operaciones[i].equals("-")){
            sum=sum-Integer.parseInt(A[i]);            
        }         

    }
    System.out.println("=  "+sum);

in this way you would get a correct calculation:

=  20
    
answered by 09.12.2016 / 02:37
source
1

I would create another array to also store the negative numbers. Let's call him B. And he would also create another whole to control the position.

String B[] = new String[100];
int posB = 0;

And then in the condition we can use the structure if-else if-else in the following way:

if(operacion.charAt(i) == '+'){
     A[pos] = aux;
     pos++;
     aux = "";
}else if((operacion.charAt(i) == '-'){
     B[posB] = aux;
     posB++;
     aux = "";
}else{
     aux = aux + operacion.charAt(i);
}

The structure if-else if-else works in the same way as a if-else although in this case it would be something like: "if you fulfill this condition do this, if you do not fulfill it check if you fulfill this other condition and if you fulfill it, do this other, if neither of the two checks are fulfilled, do this other. "

You can really use the value of aux for the two options since it is reset to empty every time you find a + or a - .

Finally you can make a loop to subtract the negative numbers:

for(int i = 0; i<posB ; i++)
{
   sum=sum-Integer.parseInt(B[i]);
}
    
answered by 09.12.2016 в 01:47
1

You can keep another vector with the signs, store them as you go through the chain and finally carry out the operation, for example:

String operacion="10+200+3000-50-400";
    int tam = operacion.length();
    String numero[] = new String[100];
    String signo[] = new String[100];
    int pos = 0;
    int sum = 0;
    String aux = "";
    String ultimoSigno = "+";
    for(int i = 0; i<tam ; i++)
    {
        if((operacion.charAt(i) == '+')||(operacion.charAt(i) == '-'))
        {
            if (aux != "") {
                numero[pos] = aux;
                signo[pos] = ultimoSigno;
                pos++;
            }
            aux = "";
            ultimoSigno = operacion.charAt(i);
        }
        else
        {
            aux = aux + operacion.charAt(i);
        }
    }
    numero[pos] = aux;
    signo[pos] = ultimoSigno;
    pos++;
    for(int i = 0; i<pos ; i++)
    {
        if (signo[i]=='+') {
          sum=sum+Integer.parseInt(A[i]);
        } else {
          sum=sum-Integer.parseInt(A[i]);
        }
    }
    System.out.println("=  "+sum);

I have edited the code here, it is likely to contain some error, but I think that only by reading it will you understand the idea.

    
answered by 09.12.2016 в 01:59
1

Considering that the integers have a sign and that a subtraction is not more than the sum of a negative, I suggest this more compact solution using regular expressions as well. Also check if there are spaces between the signs and numbers as you can see in the entry:

String operacion="5 + 45+100- 125 +5 -10";
//Quito los espacios por si los hubiera
String aux = operacion.replace(" ", "");
//Establezco el patrón 'NO número''Número'
String patron = "[^0-9][0-9]";
Pattern p = Pattern.compile(patron);
Matcher m = p.matcher(aux);

int indiceActual = 0;
Integer suma = 0;
while (m.find(indiceActual+1)){//Muevo una posición para que no se repita
    int longitud = m.start();
    suma += Integer.valueOf(aux.substring(indiceActual, longitud));
    indiceActual = longitud;
}
//Sumo el último que no cumple la condición anterior
suma += Integer.valueOf(aux.substring(indiceActual));

System.out.println(operacion + " = " + suma);

The output we get will be:

  

5 + 45 + 100- 125 +5 -10 = 20

    
answered by 09.12.2016 в 14:16