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.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
Note: Do not use the eval
built-in library function.
这道题是用stack模拟计算,本身不难,但是细节特别多。
1 使用2个stack一个存数,一个存操作
2 注意处理两位以上的数字,需要计算
3 先计算 */,因为有优先级
4 计算 +-的时候不能像*/那样取stack里两个数,进行计算然后push回去,因为这样是从右向左计算,结果会出错,eg “1-1+1”, 应该等于1,但是从右向左计算就是-1
5 用stack的时候一定先判断stack是否为空,不然不能调用top会出现runtime error
想清楚过程,是当出现数字的时候才去检查操作符,遇见操作符则直接压栈。
代码如下:
class Solution {
public:
int calculate(string s) {
stack<int> nums;
stack<char> ops;
int i = 0;
int num2 = 0;
int res = 0;
while(i < s.size()) {
if (s[i] == ' ') i++;
else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
ops.push(s[i]);
i++;
}
else {//当s[i]为数字的时候才判断op是什么
num2 = 0;
while (i < s.size() && s[i] >= '0' && s[i] <= '9') {//数字有两位以上需要计算
num2 = num2 * 10 + (s[i] - '0');
i++;
}
nums.push(num2);
if (!ops.empty()) {//记住一定先判断ops是否为空,不然不能调用top
if (ops.top() == '*') {
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
nums.push(num1 * num2);
ops.pop();
}
else if (ops.top() == '/') {
int num2 = nums.top();
nums.pop();
int num1 = nums.top();
nums.pop();
nums.push(num1 / num2);
ops.pop();
}
}
}
}
while(!ops.empty()) {//再算加减
int num = nums.top();
nums.pop();
char op = ops.top();
ops.pop();
if (op == '-') num = -num;//如何处理 减法,刚开始是取num1 num2进行计算,但是这样就是从右向左的顺序,计算结果出错
res += num;
}
res += nums.top();
nums.pop();
return res;
}
};