题解 | #牛的表达式计算器#
牛的表达式计算器
https://www.nowcoder.com/practice/261e7f01438f414c92f59c0059d3a906
考察的知识点:栈的基本操作、后缀表达式;
解答方法分析:
- 如果元素是一个操作符(“+”, “-”, “*”, “/”),则从栈st中弹出两个元素,分别表示操作数num2和num1。然后,根据操作符计算出结果并将结果压入栈st中。
- 如果元素是一个数字,则将其转换为整型并将其压入栈st中。
- 最后,返回结果。
所用编程语言:C++;
完整编程代码:↓
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param tokens string字符串vector * @return int整型 */ int calculatePostfix(vector<string>& tokens) { stack<int> st; for (string token : tokens) { int res = 0; if (token == "+") { int num2 = st.top(); st.pop(); int num1 = st.top(); st.pop(); res = num1 + num2; } else if (token == "-") { int num2 = st.top(); st.pop(); int num1 = st.top(); st.pop(); res = num1 - num2; } else if (token == "*") { int num2 = st.top(); st.pop(); int num1 = st.top(); st.pop(); res = num1 * num2; } else if (token == "/") { int num2 = st.top(); st.pop(); int num1 = st.top(); st.pop(); res = num1 / num2; } else { res = stoi(token); } st.push(res); } return st.top(); } };