#include <stack> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 给定一个后缀表达式,返回它的结果 * @param str string字符串 * @return long长整型 */ long long legalExp(string str) { // write code here stack<long long int> s; int i=0; while(!str.empty()){ if(str[i]>='0'&&str[i]<='9'){ int a=stoi(str); s.push(a); string st=to_string(a); str.erase(0,st.length()); } if(str[i]=='+'||str[i]=='*'||str[i]=='-'){ long long int x1=s.top(); s.pop(); long long int x2=s.top(); s.pop(); long long int r=0; if(str[i]=='+')r=x1+x2; if(str[i]=='-')r=x2-x1; if(str[i]=='*')r=x1*x2; s.push(r); str.erase(0,1); } if(str[i]=='#'){ str.erase(0,1); } } int num=s.size(); long long int re=s.top(); return re; } };