[UPC] Postfix Evaluation 后缀表达式求值 | 栈的简单应用
Posted PushyTao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[UPC] Postfix Evaluation 后缀表达式求值 | 栈的简单应用相关的知识,希望对你有一定的参考价值。
题目描述
In a postfix expression, operators follow their operands. For example, [ 5 2 * ] is interpreted as 5 * 2. If there are multiple operators, each operator appears after its last operand. Here are more examples, showing how postfix compares to parenthesized expressions:
6
3
+
5
∗
2
−
6\\ 3 + 5 * 2 −
6 3+5∗2− 等同
(
(
6
+
3
)
∗
5
)
–
2
)
((6 + 3) * 5) – 2)
((6+3)∗5)–2)
4
3
2
∗
+
4 \\ 3\\ 2 * +
4 3 2∗+ 等同
4
+
(
3
∗
2
)
4 + (3 * 2)
4+(3∗2)
These examples show that the operand affected by an operator can be the result of a previous calculation.
Here is what you need to do: Given an integer postfix expression, you must calculate and print its value.
输入
Each input will consist of a single test case. Your program will be run multiple times on different inputs.
A single input line will contain a postfix expression containing single digit integers and operators from the following set: { +, –, /, * } (add, subtract, divide, multiply). There will be a single space between each digit and and operator. The line will contain no more than 64 operators and numbers, total.
输出
Output will be a single integer on a line by itself.
样例输入 Copy
【样例1】
6 3 + 5 * 2 –
【样例2】
6 3 + 5 2 * *
【样例3】
4 3 2 * +
样例输出 Copy
【样例1】
43
【样例2】
90
【样例3】
10
stack<ll> st;
int main() {
char c;
while(cin >> c) {
if(isdigit(c)){
st.push(c - '0');
}else{
ll a = st.top();
st.pop();
ll b = st.top();
st.pop();
if(c == '+') st.push(a + b);
else if(c == '-') st.push(b - a);
else if(c == '*') st.push(a * b);
else st.push(b / a);
}
}
cout << st.top() << endl;
return 0;
}
/**
**/
以上是关于[UPC] Postfix Evaluation 后缀表达式求值 | 栈的简单应用的主要内容,如果未能解决你的问题,请参考以下文章
UPC / EAN / JAN Fontware为Windows / Linux / UNIX / Mac应用程序轻松创建条码