思路:
用一个栈,每次遇到运算符,都处理前面入栈的两个数字
想要取两次栈顶元素,一开始没想到怎么操作
其实就分别用num1,num2来接着就行,类型用longlong,top获取,pop()弹出
也没想到四种类型操作符怎么处理,if语句分类处理就行
注意类型 因为vector<string>类型的tokens,用string
遇到数字用stoll(num),把数字转为longlong类型
/*
* @lc app=leetcode.cn id=150 lang=cpp
*
* [150] 逆波兰表达式求值
*/
// @lc code=start
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<long long> mystack;
//因为tokens是vector<string> 类型,用string
for(string num : tokens) {
if(num == "+" || num == "-" || num == "*" || num == "/") {
long long num1 = mystack.top();
mystack.pop();
long long num2 = mystack.top();
mystack.pop();
long long result = 0;
if(num == "+") result = num2 + num1;
if(num == "-") result = num2 - num1;
if(num == "*") result = num2 * num1;
if(num == "/") result = num2 / num1;
mystack.push(result);
} else {
//是将字符串 num 转换为长整数 (long long) 并将其压入栈 mystack 中。
mystack.push(stoll(num));
}
}
return mystack.top();
}
};
// @lc code=end