0
点赞
收藏
分享

微信扫一扫

基础代码-计算后缀表达式


问题 E: 计算后缀表达式

时间限制: 1 Sec  内存限制: 128 MB

题目描述

后缀表达式是将运算符置于两个运算对象之后的一种表达方法,例如 “3+4” 用写成后缀表达式后就是 “3 4 +”,而 “3-4*5” 写成后缀表达式之后 是 “3 4 5 * -”,“(3-4)*5” 写成后缀表达式之后是 “3 4 - 5 *”。

写一个程序,读入一个后缀表达式,计算它的值。

 

输入

输入仅有一行,为待求值的后缀表达式,每两个操作符或者数字之间 用一个空格隔开。数据保证不需要判错,且中间结果可以使用 32 位有符号 整数表示。

输入的表达式中仅包含加减乘除四种运算符,且除号代表整除。

 

输出

输入一个整数,为后缀表达式的值。

样例输入

3 4 -5 *

样例输出

-5

提示

对于所有数据表达式的长度不超过 100000,且一定为合法表达式。 

模拟,从头到尾扫一遍,当出现数字+数字+符号时,将结果算出,代替这一组继续进行计算。由于后续表达式没有括号,可以省很多力气,一遍扫完就可以求出结果。

Code:

var 
q:array[0..100100] of int64;
s:ansistring;
i,top,len:longint;
t,x,y:int64;
begin
readln(s);
len:=length(s);
top:=0;
i:=1;
while i<=len do
begin
if (s[i]=' ') then
begin
inc(i);
continue;
end;
if (s[i]='-') then
begin
if (s[i+1]>='0') and (s[i+1]<='9') then
begin
t:=0;
inc(i);
while s[i]<>' ' do
begin
t:=t*10+ord(s[i])-ord('0');
inc(i);
end;
inc(top);
q[top]:=-t;
end
else
begin
x:=q[top];
y:=q[top-1];
top:=top-2;
t:=y-x;
inc(top);
q[top]:=t;
end;
end;
if (s[i]>='0') and (s[i]<='9') then
begin
t:=0;
while s[i]<>' ' do
begin
t:=t*10+ord(s[i])-ord('0');
inc(i);
end;
inc(top);
q[top]:=t;
end;
if (s[i]='+') then
begin
x:=q[top];
y:=q[top-1];
top:=top-2;
t:=y+x;
inc(top);
q[top]:=t;
end;
if (s[i]='*') then
begin
x:=q[top];
y:=q[top-1];
top:=top-2;
t:=y*x;
inc(top);
q[top]:=t;
end;
if (s[i]='/') then
begin
x:=q[top];
y:=q[top-1];
top:=top-2;
t:=y div x;
inc(top);
q[top]:=t;
end;
inc(i);
end;
writeln(q[top]);
end.

举报

相关推荐

0 条评论