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

问题 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. 
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JackflyDC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值