class Solution { public: int evalRPN(vector<string>& tokens) { int len=tokens.size(); stack<string> st; string str; for(int i=0;i<len;i++){ string cur=tokens[i]; if((cur[0]>='0'&&cur[0]<='9')||(cur[0]=='-'&&cur.size()>1&&(cur[1]>='0'&&cur[1]<='9'))){ st.push(cur); }else{ string num2=st.top(); st.pop(); string num1=st.top(); st.pop(); int num2_=stoi(num2); int num1_=stoi(num1); int res=0; if(cur=="*"){ res=num1_*num2_; }else if(cur=="+"){ res=num1_+num2_; }else if(cur=="-"){ res=num1_-num2_; }else{ res=num1_/num2_; } str=to_string(res); st.push(str); } } str=st.top(); int result=stoi(str); return result; } };
栈的简单使用,注意可能会出现负数,在判断数字的时候要分两种情况讨论。