PHP implementation:
Copy codeThe Code is as follows:
<? Php
/**
* Calculates four arithmetic expressions.
*/
Error_reporting (E_ALL );
$ Exp = '(1 + 2*(3 + 5)/4) * (3 + (5-4) * 2 )';
$ Arr_exp = array ();
For ($ I = 0; $ I <strlen ($ exp); $ I ++ ){
$ Arr_exp [] = $ exp [$ I];
}
$ Result = calcexp (array_reverse ($ arr_exp ));
Echo $ exp. '='. $ result;
Function calcexp ($ exp ){
$ Arr_n = array ();
$ Arr_op = array ();
While ($ s = array_pop ($ exp ))! = ''){
If ($ s = '('){
$ Temp = array (); $ quote = 1; $ endquote = 0;
While ($ t = array_pop ($ exp ))! = ''){
If ($ t = '('){
$ Quote ++;
}
If ($ t = ')'){
$ Endquote ++;
If ($ quote = $ endquote ){
Break;
}
}
Array_push ($ temp, $ t );
}
$ Temp = array_reverse ($ temp );
Array_push ($ arr_n, calcexp ($ temp ));
} Else if ($ s = '*' | $ s = '/'){
$ N2 = array_pop ($ exp );
If ($ n2 = '('){
$ Temp = array (); $ quote = 1; $ endquote = 0;
While ($ t = array_pop ($ exp ))! = ''){
If ($ t = '('){
$ Quote ++;
}
If ($ t = ')'){
$ Endquote ++;
If ($ quote = $ endquote)
Break;
}
Array_push ($ temp, $ t );
}
$ Temp = array_reverse ($ temp );
$ N2 = calcexp ($ temp );
}
$ Op = $ s;
$ N1 = array_pop ($ arr_n );
$ Result = operation ($ n1, $ op, $ n2 );
Array_push ($ arr_n, $ result );
} Elseif ($ s = '+' | $ s = '-'){
Array_push ($ arr_op, $ s );
} Else {
Array_push ($ arr_n, $ s );
}
}
$ N2 = array_pop ($ arr_n );
While ($ op = array_pop ($ arr_op ))! = ''){
$ N1 = array_pop ($ arr_n );
$ N2 = operation ($ n1, $ op, $ n2 );
}
Return $ n2;
}
Function operation ($ n1, $ op, $ n2 ){
Switch ($ op ){
Case '+ ':
Return intval ($ n1) + intval ($ n2 );
Break;
Case '-':
Return intval ($ n1)-intval ($ n2 );
Break;
Case '*':
Return intval ($ n1) * intval ($ n2 );
Break;
Case '/':
Return intval ($ n1)/intval ($ n2 );
Break;
}
}
Two stacks are used in this implementation method. One is used to store numbers, and the other is used to store operators. When parentheses are encountered, they are recursively entered into the brackets for calculation. The implementation method is a bit clumsy, the following describes the implementation of the "inverse polish expression" algorithm.