首页 > 其他分享 >150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation

时间:2022-12-01 20:12:10浏览次数:50  
标签:150 Reverse num2 stk break num str Polish num1


Evaluate the value of an arithmetic expression in ​​Reverse Polish Notation​​.

​+​​, ​​-​​, ​​*​​, ​​/​​. Each operand may be an integer or another expression.

Some examples:


["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6



​Subscribe​​ to see which companies asked this question

class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for (string str : tokens){
if (!isOp(str)){
stk.push(stoi(str));
}
else{
int num1 = stk.top(); stk.pop();
int num2 = stk.top(); stk.pop();
int num=0;
switch (str[0])
{
case '+':num = num1 + num2; break;
case '-':num = num2 - num1; break;
case '*':num = num1*num2; break;
case '/':num = num2 / num1; break;
default:
break;
}
stk.push(num);
}
}
return stk.top();
}
private:
bool isOp(string str){
if (str.size()==1&&(str[0] == '+' || str[0] == '-' ||
str[0] == '*' || str[0] == '/')){
return true;
}
return false;
}
};



标签:150,Reverse,num2,stk,break,num,str,Polish,num1
From: https://blog.51cto.com/u_15899184/5904033

相关文章