class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
int i=0;
int js(string s){
stack<int>a;
stack<char>b;
int n=0,t=0,f=0,x,y=0;
while(s[i]!='\0'){
if(s[i]>='0'&&s[i]<='9'){
n=n*10+(s[i]-'0');
if(!(s[i+1]>='0'&&s[i+1]<='9')){
if(f){
n*=a.top();
a.pop();
f=0;
}
a.push(n);
n=0;
}
}
else if(s[i]=='*'){
if(s[i+1]>='0'&&s[i+1]<='9')f=1;
else y=1;
}
else if(s[i]=='+'||s[i]=='-')b.push(s[i]);
else if(s[i]=='('){
i++;
x=js(s);
if(y){
x*=a.top();
a.pop();
a.push(x);
y=0;
}
else a.push(x);
goto part;
}
if(s[i+1]=='\0'||s[i]==')'){
x=0;
while(!b.empty()){
if(b.top()=='+')x+=a.top();
else if(b.top()=='-')x-=a.top();
a.pop();
b.pop();
}
x+=a.top();
a.pop();
return x;
}
part:i++;
}
return x;
}
int solve(string s) {
// write code here
int x;
x=js(s);
return x;
}
};

京公网安备 11010502036488号