题目描述:
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
The expression string contains only non-negative integers, +, -, *, / operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].
Some examples:
"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12
class Solution {
public:
int calculate(string s) {
char op='+';
int num=0;
int result=0;
stack<int> x;
int i=0;
while(i<s.size())
{
if(s[i]>='0'&&s[i]<='9')
{
num*=10;
num+=s[i]-'0';
}
else if(s[i]=='(')
{
int count=0;
int j=i;
for (;i<s.size();i++)
{
if(s[i]=='(') count++;
if(s[i]==')') count--;
if(count==0) break;
}
num=calculate(s.substr(j+1,i-j-1));
}
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/'||i==s.size()-1)
{
if(op=='+') x.push(num);
else if(op=='-') x.push(-num);
else if(op=='*')
{
int temp=x.top()*num;
x.pop();
x.push(temp);
}
else if(op=='/')
{
int temp=x.top()/num;
x.pop();
x.push(temp);
}
op = s[i];
num = 0;
}
i++;
}
while (!x.empty())
{
result+=x.top();
x.pop();
}
return result;
}
};