题目描述:
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
Note:
- You may assume that the given expression is always valid.
- Do not use the
eval
built-in library function.
计算一个只包含非负数、空格和加减乘除符号的数学表达式的结果,解题的关键在于定义一个字符记录上一次出现的运算符,当遇到数字时进行判断,如果是加号,直接将数字压栈,如果是负号,将数字的相反数压栈,如果是乘号,将栈顶出栈和当前数值计算乘积再压栈,如果是除号,将栈顶出栈和当前数值计算商再压栈。最终结果为栈中所有数值相加。
class Solution {
public:
int calculate(string s) {
stack<int> x;
int num=0;
char op='+';
for(int i=0;i<s.size();i++)
{
if(s[i]>='0'&&s[i]<='9') num=num*10+s[i]-'0';
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
{
int pre=x.top();
x.pop();
if(op=='*') x.push(pre*num);
if(op=='/') x.push(pre/num);
}
op=s[i];
num=0;
}
}
int sum=0;
while(!x.empty())
{
sum+=x.top();
x.pop();
}
return sum;
}
};