逆波兰表达式求值
根据逆波兰表示法,求表达式的值。
有效的运算符包括+,-,*,/。每个运算对象可以是整数,也可以是另一个逆波兰表达式。
说明:
- 整数除法只保留整数部分。
- 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入:["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2+1)*3)=9
代码如下(C++):
class Solution {
public:
int ans; // 结果
int evalRPN(vector<string>& tokens) {
stack<int> st; // 定义栈
int ans_1,ans_2; // 定义俩数当缓存
for(auto v_mate : tokens){ // 遍历输入 tokens
if(v_mate == "+"){ // 如果遇到 运算符号
ans_1 = st.top(); // 推出之前的两个数字
st.pop();
ans_2 = st.top();
st.pop();
st.push(ans_2 + ans_1); // 进行运算,注意,先推出的在前
}
else if(v_mate == "-"){ // 减法类似
ans_1 = st.top();
st.pop();
ans_2 = st.top();
st.pop();
st.push(ans_2 - ans_1); // 注意是 ans_2 - ans_1
}
else if(v_mate == "*"){
ans_1 = st.top();
st.pop();
ans_2 = st.top();
st.pop();
st.push(ans_2 * ans_1);
}
else if(v_mate == "/"){
ans_1 = st.top();
st.pop();
ans_2 = st.top();
st.pop();
st.push(ans_2 / ans_1);
}
else{ // 如果不是运算符,就把字符串数字转为整型数字推入栈中
st.push(atoi(v_mate.c_str()));
}
}
ans = st.top(); // 栈中最后推入的就是结果
return ans;
}
};
放在最后
如果您喜欢我的文章,拜托点赞+收藏+关注,博主会根据大家喜好来推出相关系列文章~
更多精彩内容也可以访问我的博客Aelous-BLog