Description
小明在你的帮助下,破译了Ferrari设的密码门,正要往前走,突然又出现了一个密码门,门上有一个算式,其中只有“(”、“)”、“0-9”、“+”、“-”、“*”、“/”、“^”,求出的值就是密码。小明的数学学得不好,还需你帮他的忙。(“/”用整数除法)
Input
输入有一行是一个算式(算式长度<=30)。
Output
输出算式的值(所有数据在2^31-1内)。
Sample Input
1+(3+2)*(7^2+6*9)/(2)
Sample Output
258
解题思路:读入字符串,把数字和符号分别放入两个栈,根据运算符的优先级对两个栈进行相应的操作。
程序:
const
maxn=100;
var
number:array [0..maxn] of longint;
symbol:array [1..maxn] of char;
s,t:string;
i,p,j:longint;
procedure push;
begin
inc(p);
symbol[p]:=s[i];
end;
procedure pop;
var
i,temp:longint;
begin
dec(p);
temp:=number[p];
case symbol[p+1] of
'+':inc(number[p],number[p+1]);
'-':dec(number[p],number[p+1]);
'*':number[p]:=number[p]*number[p+1];
'/':number[p]:=number[p] div number[p+1];
'^':for i:=1 to number[p+1]-1 do number[p]:=number[p]*temp;
end;
end;
function can:boolean;
begin
can:=true;
if (s[i] in ['+','-']) and (symbol[p]<>'(') then exit;
if (s[i] in ['*','/']) and (symbol[p] in ['*','/','^']) then exit;
can:=false;
end;
begin
readln(s);
s:='('+s+')';
i:=1;
while i<=length(s) do
begin
while s[i]='(' do
begin
push;
inc(i);
end;
j:=i;
repeat
inc(i);
until (s[i]<'0') or (s[i]>'9');
t:=copy(s,j,i-j);
val(t,number[p]);
repeat
if s[i]=')' then
begin
while symbol[p]<>'(' do
pop;
dec(p);
number[p]:=number[p+1];
end
else
begin
while can do
pop;
push;
end;
inc(i);
until (i>length(s)) or (s[i-1]<>')');
end;
writeln(number[0]);
end.