计算问题(栈)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值