题解 | 牛牛与后缀表达式
牛牛与后缀表达式
https://www.nowcoder.com/practice/a1a4f178f6ff4188890e51da1cc8ce10
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
long long legalExp(string str) {
// write code here
long long now=0;
stack<long long> st;
for(int i=0;i<str.length();i++)
{
if(str[i]>='0'&&str[i]<='9'){
now=now*10+str[i]-'0';
}
else if(str[i]=='#'){
st.push(now);
now=0;
}
else{
long long x2=st.top();
st.pop();
long long x1=st.top();
st.pop();
if(str[i]=='+') st.push(x1+x2);
else if(str[i]=='-') st.push(x1-x2);
else if(str[i]=='*') st.push(x1*x2);
}
}
return st.top();
}
};
查看9道真题和解析