function Eval(Term:
string): Integer;
function _Eval(term:
string;
var i: Integer): Integer;
const
isNone = 0;
isNum = 1;
isOp = 2;
var
numStack:
array[0..10]
of Integer;
number, code, sign, sp, j: Integer;
Ops:
string;
c: Char;
function OpOrder(c: Char): Integer;
begin
if c = '
$'
then
Result := -1
else
Result := (Pos(c, '
+-*/') + 1)
div 2;
end;
begin
fillchar(numstack, sizeof(numstack), 0);
sign := 1;
Ops := '
$';
SP := 0;
number := 0;
Result := 0;
code := isNone;
while i < length(term)
do begin
inc(i);
c := term[i];
case c
of
'
0'..'
9':
begin
number := 10 * number + ord(c) - 48;
code := isNum;
end;
'
(':
begin
number := _Eval(term, i);
code := isNum;
end;
'
': continue;
'
+', '
-', '
*', '
/', '
)':
begin
if code = isNum
then begin
numStack[SP] := sign * number;
sign := 1;
inc(SP);
code := isNone;
number := 0;
end else if code = isOp
then begin
if c = '
-'
then
sign := -sign;
Continue
end;
code := isop;
if Length(Ops) > 1
then begin
while opOrder(c) <= OpOrder(Ops[Length(Ops)])
do begin
dec(sp);
case Ops[Length(Ops)]
of
'
*': numstack[sp - 1] := numstack[sp - 1] * numstack[sp];
'
/': numstack[sp - 1] := numstack[sp - 1]
div numstack[sp];
'
+': numstack[sp - 1] := numstack[sp - 1] + numstack[sp];
'
-': numstack[sp - 1] := numstack[sp - 1] - numstack[sp];
end;
numStack[sp] := 0;
setLength(Ops, length(Ops) - 1);
end;
end;
Ops := Ops + c;
if c = '
)'
then begin
number := NumStack[0];
break;
end;
end;
end;
end;
result := Number;
end;
var
i: Integer;
begin
i := 0;
Result := _Eval('
(' + term + '
)', i);
end;