227. Basic Calculator II
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem requires us to evaluate a mathematical expression given as a string. The expression includes non-negative integers and the four basic operators: +, -, *, /. The key challenge is to correctly handle operator precedence, where multiplication (*) and division (/) must be performed before addition (+) and subtraction (-). We also need to handle integer division, which truncates toward zero.
Solution
Basic Calculator II in Python
class Solution:
def calculate(self, s: str) -> int:
stack = []
num = 0
op = '+'
s += '+' # Append a sentinel operator to handle the last number.
for char in s:
if char.isdigit():
# Build the current number.
num = num * 10 + int(char)
elif char.isspace():
# Skip spaces.
continue
else:
# An operator is found, process the `num` with the `op`.
if op == '+':
stack.append(num)
elif op == '-':
stack.append(-num)
elif op == '*':
stack.append(stack.pop() * num)
elif op == '/':
# Use int() for truncation towards zero.
stack.append(int(stack.pop() / num))
# Update the operator and reset the number.
op = char
num = 0
# Sum up all numbers in the stack for the final result.
return sum(stack)
Basic Calculator II in Java
class Solution {
public int calculate(String s) {
if (s == null || s.length() == 0) {
return 0;
}
Stack<Integer> stack = new Stack<>();
int num = 0;
char op = '+';
s += '+'; // Append a sentinel operator to handle the last number.
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
// Build the current number.
num = num * 10 + (c - '0');
} else if (c == ' ') {
// Skip spaces.
continue;
} else {
// An operator is found, process the `num` with the `op`.
if (op == '+') {
stack.push(num);
} else if (op == '-') {
stack.push(-num);
} else if (op == '*') {
stack.push(stack.pop() * num);
} else if (op == '/') {
stack.push(stack.pop() / num); // Integer division in Java truncates toward zero.
}
// Update the operator and reset the number.
op = c;
num = 0;
}
}
// Sum up all numbers in the stack for the final result.
int result = 0;
for (int val : stack) {
result += val;
}
return result;
}
}
Basic Calculator II in C++
class Solution {
public:
int calculate(string s) {
stack<long> st;
long num = 0;
char op = '+';
s += '+'; // Append a sentinel operator to handle the last number.
for (char c : s) {
if (isdigit(c)) {
// Build the current number.
num = num * 10 + (c - '0');
} else if (isspace(c)) {
// Skip spaces.
continue;
} else {
// An operator is found, process the `num` with the `op`.
if (op == '+') {
st.push(num);
} else if (op == '-') {
st.push(-num);
} else if (op == '*') {
long top = st.top();
st.pop();
st.push(top * num);
} else if (op == '/') {
long top = st.top();
st.pop();
st.push(top / num); // Integer division in C++ truncates toward zero.
}
// Update the operator and reset the number.
op = c;
num = 0;
}
}
// Sum up all numbers in the stack for the final result.
long res = 0;
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
};
Basic Calculator II in TypeScript
function calculate(s: string): number {
s += '+'; // Append a sentinel operator to handle the last number.
const stack: number[] = [];
let num = 0;
let op = '+';
for (const char of s) {
if (char >= '0' && char <= '9') {
// Build the current number.
num = num * 10 + parseInt(char, 10);
} else if (char === ' ') {
// Skip spaces.
continue;
} else {
// An operator is found, process the `num` with the `op`.
if (op === '+') {
stack.push(num);
} else if (op === '-') {
stack.push(-num);
} else if (op === '*') {
stack.push(stack.pop()! * num);
} else if (op === '/') {
const top = stack.pop()!;
// Math.trunc() performs truncation towards zero.
stack.push(Math.trunc(top / num));
}
// Update the operator and reset the number.
op = char;
num = 0;
}
}
// Sum up all numbers in the stack for the final result.
return stack.reduce((acc, val) => acc + val, 0);
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.