PHP Implementation:
Copy Code code as follows:
<?php
/**
* Calculation of 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 = = '/') {
$n 2 = Array_pop ($EXP);
if ($n 2 = = ' (') {
$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);
$n 2 = calcexp ($temp);
}
$op = $s;
$n 1 = array_pop ($arr _n);
$result = operation ($n 1, $op, $n 2);
Array_push ($arr _n, $result);
}elseif ($s = = ' + ' | | | $s = = ') {
Array_push ($arr _op, $s);
}else{
Array_push ($arr _n, $s);
}
}
$n 2 = Array_pop ($arr _n);
while (($op = Array_pop ($arr _op))!= ') {
$n 1 = array_pop ($arr _n);
$n 2 = operation ($n 1, $op, $n 2);
}
return $n 2;
}
function operation ($n 1, $op, $n 2) {
Switch ($OP) {
Case ' + ':
Return Intval ($n 1) + intval ($n 2);
Break
Case '-':
Return Intval ($n 1)-Intval ($n 2);
Break
Case ' * ':
Return Intval ($n 1) * Intval ($n 2);
Break
Case '/':
Return Intval ($n 1)/Intval ($n 2);
Break
}
}
This implementation uses two stacks, one to store the numbers, one to store the operators, and after the parentheses are recursive into parentheses to operate, the implementation is a bit clumsy, followed by the "Reverse Polish expression" algorithm implementation.