首页 > 其他分享 >基础代码-计算后缀表达式

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

时间:2022-11-22 18:32:40浏览次数:55  
标签:begin end 后缀 代码 top 表达式 inc


问题 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.

标签:begin,end,后缀,代码,top,表达式,inc
From: https://blog.51cto.com/u_15888102/5878331

相关文章

  • 基础代码-线段
    问题B:线段时间限制:1Sec  内存限制:128MB题目描述1.询问+LR增加一条线段[L,R],你的程序应该输出有多少条线段被该线段包含(非严格)。2.询问-L......
  • JS正则表达式、while循环
    <!-- while循环 while循环会在指定条件为真时循环执行代码块。 语法: while(条件) { 需要执行的代码 } do/while循环是while循环的变体。该循环......
  • javascript-代码随想录训练营day6
    242.有效的字母异位词题目链接:https://leetcode.cn/problems/valid-anagram/题目描述:给定两个字符串s和t,编写一个函数来判断t是否是s的字母异位词。注意:若s......
  • 使用MSIL采用Emit方式实现C#的代码生成与注入常用代码
    本文主要使用微软提供的一套C#的API函数,通过这些API函数,可以对已经编译过的.Net体系生成的EXE,DLL文件进行修改,而不是修改源码编译的方式,来完成新功能的加入、或者原有功......
  • ECharts – 饼状图图代码实例及其注释详解
    mytextStyle={color:"#333",//文字颜色fontStyle:"normal",//italic斜体oblique倾斜fontWeight:"normal",//文字粗细boldbolderl......
  • ECharts – 折线图代码实例及注释
    mytextStyle={color:"#333",//文字颜色fontStyle:"normal",//italic斜体oblique倾斜fontWeight:"normal",//文字粗细boldbolderl......
  • ECharts – 柱形图代码实例及其注释详解
    mytextStyle={color:"#333",//文字颜色fontStyle:"normal",//italic斜体oblique倾斜fontWeight:"normal",//文字粗细boldbolderl......
  • Java实现网络爬虫 案例代码
    Java实现网络爬虫案例代码需求说明搭建开发环境,实现《三国演义》全文保存在本地 步骤分析访问网址:http://www.shicimingju.com/book/sanguoyanyi.html分析网站URL......
  • HX学习之常用代码块
    查看内建的代码块,点击菜单-工具-代码块设置,选择要查看的语言的代码块。通用js代码块iff:简单ifforr:for循环结构体fori:for循环结构体并包含ifunn:函数funa:匿名函数......
  • 小程序canvas2D绘制印章,话不多说,直接上代码
    效果图:  CanvasContext是旧版的接口,不维护了,新版Canvas2D接口与Web一致  官方文档: https://developers.weixin.qq.com/miniprogram/dev/api/canvas/......