227. Basic Calculator II
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.
方法1: stack
思路:
在Basic Calculator的基础上如何修改呢?回忆一下那道题:遇到左括号推栈,遇到右括号弹栈,而且是operator和operand各用一个栈。这道题虽然也是栈,但原则完全不一样。这里只用一个栈,用来存数字。操作如下:
- 遇到加减法的时候,将operator * operand 算好压栈。
- 遇到乘除法,取栈顶元素与当前元素运算,结果再压回栈。
- 结束时所有元素依次出栈并求和。
class Solution {
public:
int calculate(string s) {
stack<int> st;
long num = 0;
int result = 0;
int op ='+';
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (isdigit(c)) {
num = num * 10 + c - '0';
}
if (!isdigit(c) && !isspace(c) || i == s.size() - 1){
if (op == '+') st.push(num);
if (op == '-') st.push(-num);
if (op == '*' || op == '/') {
int top = st.top();
st.pop();
if (op == '*') st.push(top * num);
if (op == '/') st.push(top / num);
}
op = s[i];
num = 0;
}
}
while (!st.empty()) {
result += st.top();
st.pop();
}
return result;
}
};