题目描述:
主要思路:
此题目最主要的问题是如何确定当前数字是加还是减,看了题解之后发现可以用一个栈巧妙地实现。
class Solution {
public:
int calculate(string s) {
stack<int> ops;
ops.push(1);
int sign=1,ans=0;
int n=s.length();
int i=0;
while(i<n)
{
if(s[i]==' ')
;
else if(s[i]=='+')
sign=ops.top();
else if(s[i]=='-')
sign=-ops.top();
else if(s[i]=='(')
ops.push(sign);
else if(s[i]==')')
ops.pop();
else
{
long num=0;
while(i<n&&s[i]>='0'&&s[i]<='9')
{
num=num*10+s[i]-'0';
++i;
}
--i;
ans+=sign*num;
}
++i;
}
return ans;
}
};