波兰表达式也称之为前缀表达式,即运算符放置于操作数之前。 计算波兰表达式的值的方法: (1)从后往前遍历表达式。 (2)遇到数字直接入栈。 (3)遇到运算符,取出两个数字,第一个作为操作数,第二作为被操作数,执行相应的运算。将运算的结果继续入栈。 (4)当表达式遍历完时,此时栈顶元素即为计算结果。
int cal(string s) {
stack<int> st;
for (int i=s.length()-1; i>=0; --i) {
if (isdigit(s[i])) {
st.push(s[i] - '0');
} else if (s[i] == '+') {
int a = st.top(); st.pop();
int b = st.top(); st.pop();
st.push(a+b);
} else if (s[i] == '-') {
int a = st.top(); st.pop();
int b = st.top(); st.pop();
st.push(a-b);
} else if (s[i] == '*') {
int a = st.top(); st.pop();
int b = st.top(); st.pop();
st.push(a*b);
} else if (s[i] == '/' ) {
int a = st.top(); st.pop();
int b = st.top(); st.pop();
st.push(a/b);
}
}
return st.top();
}
int main() {
string s = "-+8*3-27/42";
cout << cal(s) << endl;
}