题目描述
所谓后缀表达式是指这样的一个表达式:式中不再引用括号,运算符号放在两个运算对象之后,所有计算按运算符号出现的顺序,严格地由左而右新进行(不用考虑运算符的优先级)。
本题中运算符仅包含 +-*/+-*/。保证对于 // 运算除数不为 0。特别地,其中 // 运算的结果需要向 0 取整(即与 C++ /
运算的规则一致)。
如:3*(5-2)+73*(5-2)+7 对应的后缀表达式为:3.5.2.-*7.+@3.5.2.-*7.+@。在该式中,@
为表达式的结束符号。.
为操作数的结束符号。
输入格式
输入一行一个字符串 �s,表示后缀表达式。
输出格式
输出一个整数,表示表达式的值。
这道题不需要考虑运算符号间的优先级,所以还是比较简单的,重在理解题意,不要过多的关注'.'和’@‘这个符号,没啥用
代码如下
#include<iostream>
#include<stack>
using namespace std;
int main()
{
string a;
cin>>a;
stack<int> p;
for(int i=0;i<a.size();i++)
{
if(a[i]>='0'&&a[i]<='9')
{
int j=i;
int need=0;
while(a[j]!='.')
{
int temp=a[j]-'0';
need=need*10+temp; //两位数及以上得先获得数字再压入栈内
j++;
}
i=j-1; //切记i的值也发生改变
p.push(need);
}
else if(a[i]=='+')
{
int need=0;
need+=p.top();
p.pop();
need+=p.top();
p.pop();
p.push(need);
}
else if(a[i]=='-')
{
int need=0;
int temp=p.top();
p.pop();
need=p.top()-temp;
p.pop();
p.push(need);
}
else if(a[i]=='*')
{
int need=0;
need=p.top();
p.pop();
need*=p.top();
p.pop();
p.push(need);
}
else if(a[i]=='/')
{
int need=0;
int temp=p.top();
p.pop();
need=p.top()/temp;
p.pop();
p.push(need);
}
}
cout<<p.top()<<endl;
}
有个题目是计算表达式,需要考虑每个运算符号的权重,可以看看
题目描述:
- 数据保证给定的表达式合法。
- 题目保证符号
-
只作为减号出现,不会作为负号出现,例如,-1+2
,(2+2)*(-(1+1)+2)
之类表达式均不会出现。 - 题目保证表达式中所有数字均为正整数。
- 题目保证表达式在中间计算过程以及结果中,均不超过 231−1231−1。
- 题目中的整除是指向 00 取整,也就是说对于大于 00 的结果向下取整,例如 5/3=15/3=1,对于小于 00 的结果向上取整,例如 5/(1−4)=−15/(1−4)=−1。
- C++和Java中的整除默认是向零取整;Python中的整除
//
默认向下取整,因此Python的eval()
函数中的整除也是向下取整,在本题中不能直接使用。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
stack<int> num;
stack<char> op;
void eval()
{
auto b = num.top(); num.pop();
auto a = num.top(); num.pop();
auto c = op.top(); op.pop();
int x;
if (c == '+') x = a + b;
else if (c == '-') x = a - b;
else if (c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
string str;
cin >> str;
for (int i = 0; i < str.size(); i ++ )
{
auto c = str[i];
if (isdigit(c))
{
int x = 0, j = i;
while (j < str.size() && isdigit(str[j]))
x = x * 10 + str[j ++ ] - '0';
i = j - 1;
num.push(x);
}
else if (c == '(') op.push(c);
else if (c == ')')
{
while (op.top() != '(') eval();
op.pop();
}
else
{
while (op.size() && op.top() != '(' && pr[op.top()] >= pr[c]) eval();
op.push(c);
}
}
while (op.size()) eval();
cout << num.top() << endl;
return 0;
}
上面的代码原作者是 :yxc
链接:https://www.acwing.com/activity/content/code/content/972603/
来源:AcWing