Skip to content

Instantly share code, notes, and snippets.

@xzhang311
Last active March 22, 2016 19:58
class Solution {
public:
int evalRPN(vector<string>& tokens) {
if(tokens.size()==1)
return stoi(tokens[0]);
int res=0;
stack<int> myStack;
int p=0;
while(!myStack.empty()||p!=tokens.size()){
string s=tokens[p];
if(s.compare("+")==0||s.compare("-")==0||s.compare("*")==0||s.compare("/")==0){
int op0=myStack.top(); myStack.pop();
int op1=myStack.top(); myStack.pop();
int r=0;
switch(s[0]){
case '+': r=(op1)+(op0); break;
case '-': r=(op1)-(op0); break;
case '*': r=(op1)*(op0); break;
case '/': r=(op1)/(op0); break;
}
if(p!=tokens.size()-1||!myStack.empty())
myStack.push(r);
res=r;
}else{
int i=stoi(s);
myStack.push(i);
}
p++;
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment