题解 | #表达式求值#
表达式求值
https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
int solve(string s) {
// write code here
stack<int> st_num;
stack<char> st_op;
st_op.push('#');
int a=0,b=0,number=0,is_num=0;
int i = 0,n=s.length();
s+='#';
char op='#';
while(i<n||st_op.top()!='#')
{
is_num=0;
number = 0;
while(s[i]>='0'&&s[i]<='9'&&i<n)
{
is_num = 1;
number = number*10 + (s[i]-'0');
i++;
}
if(is_num==1)
{
st_num.push(number);
}
op = st_op.top();
if(op=='#')
{
st_op.push(s[i]);
i++;
}
else if(op=='+')
{
if(s[i]=='*'||s[i]=='(')
{
st_op.push(s[i]);
i++;
}
else
{
b = st_num.top();
st_num.pop();
a = st_num.top();
st_num.pop();
st_num.push(a+b);
st_op.pop();
}
}
else if(op=='-')
{
if(s[i]=='*'||s[i]=='(')
{
st_op.push(s[i]);
i++;
}
else
{
b = st_num.top();
st_num.pop();
a = st_num.top();
st_num.pop();
st_num.push(a-b);
st_op.pop();
}
}
else if(op=='*')
{
if(s[i]=='(')
{
st_op.push(s[i]);
i++;
}
else
{
b = st_num.top();
st_num.pop();
a = st_num.top();
st_num.pop();
st_num.push(a*b);
st_op.pop();
}
}
else if(op=='(')
{
if(s[i]==')')
{
st_op.pop();
i++;
}
else
{
st_op.push(s[i]);
i++;
}
}
}
return st_num.top();
}
};