Given a string s
which represents an expression, evaluate this expression and return its value.
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 [-2<sup>31</sup>, 2<sup>31</sup> - 1]
.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval()
.
Test Cases
Example 1:
Input: s = "3+2*2"
Output: 7
Example 2:
Input: s = " 3/2 "
Output: 1
Example 3:
Input: s = " 3+5 / 2 "
Output: 5
Constraints:
1 <= s.length <= 3 * 10<sup>5</sup>
s
consists of integers and operators('+', '-', '*', '/')
separated by some number of spaces.s
represents a valid expression.- All the integers in the expression are non-negative integers in the range
[0, 2<sup>31</sup> - 1]
. - The answer is guaranteed to fit in a 32-bit integer.
Solution
class Solution {
public int calculate(String s) {
Stack<Integer> st = new Stack<>();
int num = 0;
char operator = '+';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
}
if (isOperator(c) || i == s.length() - 1) {
if (operator == '+') st.push(num);
else if (operator == '-') st.push(-num);
else if (operator == '*') st.push(st.pop() * num);
else if (operator == '/') st.push(st.pop() / num);
num = 0;
operator = c;
}
}
int ans = 0;
while (!st.isEmpty()) {
ans += st.pop();
}
return ans;
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
}
class Solution:
def calculate(self, s: str) -> int:
def update(op, v):
if op == "+": stack.append(v)
if op == "-": stack.append(-v)
if op == "*": stack.append(stack.pop() * v) #for BC II and BC III
if op == "/": stack.append(int(stack.pop() / v)) #for BC II and BC III
it, num, stack, sign = 0, 0, [], "+"
while it < len(s):
if s[it].isdigit():
num = num * 10 + int(s[it])
elif s[it] in "+-*/":
update(sign, num)
num, sign = 0, s[it]
elif s[it] == "(": # For BC I and BC III
num, j = self.calculate(s[it + 1:])
it = it + j
elif s[it] == ")": # For BC I and BC III
update(sign, num)
return sum(stack), it + 1
it += 1
update(sign, num)
return sum(stack)