227. Basic Calculator II
Asked at 26Meta90Apple59Amazon49Bloomberg39Microsoft35Google29Snap90TikTok67Rokt98Tesla88Rivian81IXL77Verkada76Zoox74Airbnb66ByteDance59Adobe55Expedia54Zoho52Palo Alto Networks50DoorDash48Uber44Yandex42Snowflake39DE Shaw38Oracle35
Problem
Evaluate the expression s containing non-negative integers, + - * / and spaces (no parentheses), with the usual precedence. Division truncates toward zero.
Example: "3+2*2" → 7; " 3/2 " → 1
No parentheses, but * / bind tighter. When an operator (or the end) is reached, apply the previous operator: +x / -x push, * / / combine with the top. Sum the stack.
Complexity: O(n).
class Solution:
def calculate(self, s: str) -> int:
st, num, op = [], 0, "+"
for i, ch in enumerate(s):
if ch.isdigit():
num = num * 10 + int(ch)
if ch in "+-*/" or i == len(s) - 1:
if op == "+": st.append(num)
elif op == "-": st.append(-num)
elif op == "*": st.append(st.pop() * num)
else: st.append(int(st.pop() / num))
op, num = ch, 0
return sum(st)
assert Solution().calculate("3+2*2") == 7
assert Solution().calculate(" 3/2 ") == 1
assert Solution().calculate(" 3+5 / 2 ") == 5
assert Solution().calculate("14-3/2") == 13
class Solution {
public int calculate(String s) {
Deque<Integer> st = new ArrayDeque<>();
int num = 0;
char op = '+';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) num = num * 10 + (c - '0');
if ("+-*/".indexOf(c) >= 0 || i == s.length() - 1) {
if (op == '+') st.push(num);
else if (op == '-') st.push(-num);
else if (op == '*') st.push(st.pop() * num);
else st.push(st.pop() / num);
op = c; num = 0;
}
}
int res = 0;
for (int x : st) res += x;
return res;
}
}
func calculate(s string) int {
st, num, op := []int{}, 0, byte('+')
for i := 0; i < len(s); i++ {
ch := s[i]
if ch >= '0' && ch <= '9' {
num = num*10 + int(ch-'0')
}
if strings.IndexByte("+-*/", ch) >= 0 || i == len(s)-1 {
switch op { // apply the previous operator to num
case '+':
st = append(st, num)
case '-':
st = append(st, -num)
case '*':
st[len(st)-1] *= num
case '/':
st[len(st)-1] /= num
}
op, num = ch, 0
}
}
sum := 0
for _, x := range st {
sum += x
}
return sum
}