题目描述
逆波兰式就是后缀表达式,它的定义如下:
- 单个数字如6,8等都是后缀表达式;
- 如果$e_1$,$e_2$都是后缀表达式,则$e_1 e_2 +$、$e_1 e_2 −$、$e_1 e_2 ∗$ 都是后缀表达式;
- 不满足以上两条规则的表达式都不是后缀表达式。
给定一个后缀表达式(保证合法),请计算表达式的值,并输出它模10的余数。
注意,为了方便起见,我们省略了除法,同时也规定在表达式中出现的数字只能由一位数构成。
输入描述
一个字符序列:表示输入的后缀表达式。每个字符间用一个空格分开。保证输入字符只可能出现0
到9
及+
,-
,*
三种运算符,且构成一个合法的后缀表达式。
数据范围
记输入的可见字符数量为$n$,
- 对于50%的数据,$1≤n≤100$;
- 对于100%的数据,$1≤n≤100,000$。
输出描述
单个数字:表示表达式的值模 10 的余数,注意余数必须大于或等于零。
输入样例
3 4 +
输出样例
7
#include<bits/stdc++.h>
using namespace std;
stack<int> st;
string line;
int main() {
getline(cin,line);
for(int i=0; i<line.size(); i++) {
char tem=line[i];
if(tem==' ') continue;
if(tem<='9' and tem>='0') {
st.push(tem-'0');
continue;
}
int now=0;
int b= st.top();
st.pop();
int a=st.top();
st.pop();
if(tem=='+') st.push((a+b)%10);
if(tem=='-') st.push((a-b)%10);
if(tem=='*') st.push(a*b%10);
}
int ans=st.top();
ans=ans%10;
if (ans<0) ans=10+ans;
cout<<ans;
return 0;
}