求解逆波兰表达式(Calculate the reverse Polish notation)。有关栈的最基础应用。
来源:互联网 发布:社会主义生产方式知乎 编辑:程序博客网 时间:2024/05/29 03:51
描述
编写函数int add(char s[]);计算字符串形式的逆波兰表达式(即两个操作数在前,计算符在后)。本题内,保证每个操作数均为1位数。操作符有’+’,’-‘,’*’,’/’四种。且保证计算过程中除法运算全部为整数除法,结果为整数。
如23+4*,,结果20
Write a function int add (char s []); Calculate the string form of reverse Polish notation (ie, the first is two operands, then the operator). This problem, to ensure that each of the operands are 1-digit. The operator have only four: ‘+’, ‘-‘, ‘*’, ‘/’. And to ensure that the division operation in the calculation process for all the integer division, the result is an integer.
Such as 23+4*, the result is 20.
输入
一行字符串,长度不超过20。
Input a string, no more then 20 characters.
输出
逆波兰表达式的计算结果。
Output the result of reverse Polish notation.
输入样例
23+4*
输出样例
20
#include<iostream> #include<stack> //栈的头文件using namespace std;stack <int> s1; //声明一个栈int calcu(int n1,int n2,char op){ int result; if(op=='+') result=n1+n2; else if(op=='-') result=n1-n2; else if(op=='*') result=n1*n2; else result=n1/n2; return result;}int main(){ char s[1000]; cin>>s; int i=0,num1,num2,result; while(s[i]) { if(s[i]>=48&&s[i]<=57) { s1.push(s[i]-'0');//如果是数字则向栈中压入一个数字 result=s1.top(); /*如果字符串中一个数字(没有运算符),则把这个数字当作结果输出。 这是一个数据陷阱,如果没有这条语句,这种情况下输出的result是任意值。*/ } else//在遇到运算符时 //栈中现在应该有先输入的数据num1和后输入的数据num2。 { num2=s1.top(); //因为栈中的数据是后进先出的,在栈顶的是刚刚输入的数据num2。 //不能颠倒num1和num2的顺序,否则在减和除运算时会出现错误。 s1.pop();//从栈顶弹出一个成员num2,栈中只剩num1。 num1=s1.top(); s1.pop();//现在栈是空的 result=calcu(num1,num2,s[i]); //计算num1和num2的运算结果 s1.push(result);//将结果压入栈中,成为下一次运算的num1. } i++; } cout<<result<<endl;}
- 求解逆波兰表达式(Calculate the reverse Polish notation)。有关栈的最基础应用。
- 逆波兰表达式(Reverse Polish Notation)
- Evaluate Reverse Polish Notation 逆波兰表达式
- Reverse Polish Notation.逆波兰表达式,笔记
- leetcode Evaluate Reverse Polish Notation(计算逆波兰表达式)
- LeetCode Reverse Polish Notation求逆波兰表达式值
- Java Evaluate Reverse Polish Notation(逆波兰表达式)
- [Leetcode] Evaluate Reverse Polish Notation 逆波兰表达式
- leetcode_2 Evaluate Reverse Polish Notation 逆波兰表达式
- 【LintCode】Evaluate Reverse Polish Notation 逆波兰表达式求值
- 逆波兰表达式求值(Evaluate Reverse Polish Notation)
- LeetCode:150. Evaluate Reverse Polish Notation(逆波兰表达式)
- Java实现逆波兰表达式(Evaluate Reverse Polish Notation)
- 150. Evaluate Reverse Polish Notation 逆波兰表达式
- calculate reverse polish notation
- LeetCode OJ 之 Evaluate Reverse Polish Notation (求逆波兰表达式的值)
- leetcode 150. Evaluate Reverse Polish Notation 逆波兰表达式的计算
- 2. evaluate-reverse-polish-notation 后缀表达式的求解
- tomcat 6 el表达式报错的问题
- tf.placeholder使用说明
- 设计模式——桥接模式
- spring利用mybatis PageHelper分页
- GDCA参加第42次CA/B论坛(CA/Browser Forum)国际工作会议
- 求解逆波兰表达式(Calculate the reverse Polish notation)。有关栈的最基础应用。
- NUnits 配置问题
- openjdk和jdk的区别
- windows环境下安装selenium
- nginx+redis+tomcat三级缓存架构讲解
- GML C++ Camera Calibration Toolbox 相机标定畸变矫正
- Springmvc学习(06)-异常处理
- VC控制excel
- 自定义View之RGB颜色变化Paint画笔颜色过滤器setColorFilter,LightingColorFilter光照过滤器