KatInterview

224. Basic Calculator

HardSolutions in Python, Java, C++, TypeScript

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 asks us to implement a basic calculator to evaluate a string expression containing numbers, +, -, (, and ). The main challenge lies in correctly handling the order of operations, specifically the precedence of parentheses. Expressions inside parentheses must be evaluated first.

Solution

Basic Calculator in Python

class Solution:
    def calculate(self, s: str) -> int:
        stack = []
        result = 0
        num = 0
        sign = 1  # 1 for +, -1 for -

        for char in s:
            if char.isdigit():
                num = num * 10 + int(char)
            elif char == '+':
                result += sign * num
                num = 0
                sign = 1
            elif char == '-':
                result += sign * num
                num = 0
                sign = -1
            elif char == '(':
                # Push the current result and sign onto the stack
                stack.append(result)
                stack.append(sign)
                # Reset for the new sub-expression
                result = 0
                sign = 1
            elif char == ')':
                result += sign * num
                num = 0
                
                # Pop sign and result from parent expression
                # result is now the value of the sub-expression
                result *= stack.pop()  # pop sign
                result += stack.pop()  # pop result
            # Ignore spaces
        
        # Add the last number to the result
        if num != 0:
            result += sign * num
            
        return result

Basic Calculator in Java

class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        int result = 0;
        int num = 0;
        int sign = 1; // 1 for positive, -1 for negative

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            } else if (c == '+') {
                result += sign * num;
                num = 0;
                sign = 1;
            } else if (c == '-') {
                result += sign * num;
                num = 0;
                sign = -1;
            } else if (c == '(') {
                // Push the current result and sign onto the stack
                stack.push(result);
                stack.push(sign);
                // Reset for the sub-expression
                result = 0;
                sign = 1;
            } else if (c == ')') {
                result += sign * num;
                num = 0;

                // Pop the sign and result from the parent expression
                result *= stack.pop(); // Multiply by the sign before the parenthesis
                result += stack.pop(); // Add the result from before the parenthesis
            }
            // Ignore spaces
        }

        // Add the last number to the result
        if (num != 0) {
            result += sign * num;
        }

        return result;
    }
}

Basic Calculator in C++

class Solution {
public:
    int calculate(string s) {
        stack<int> st; // Stack to store intermediate results and signs
        long long result = 0;
        long long num = 0;
        int sign = 1; // 1 for positive, -1 for negative

        for (char c : s) {
            if (isdigit(c)) {
                num = num * 10 + (c - '0');
            } else if (c == '+') {
                result += sign * num;
                num = 0;
                sign = 1;
            } else if (c == '-') {
                result += sign * num;
                num = 0;
                sign = -1;
            } else if (c == '(') {
                // Push the current result and sign onto the stack
                st.push(result);
                st.push(sign);
                // Reset for the sub-expression
                result = 0;
                sign = 1;
            } else if (c == ')') {
                result += sign * num;
                num = 0;

                // Pop the sign and result from the parent expression
                result *= st.top(); // a * sign
                st.pop();
                result += st.top(); // a * sign + b
                st.pop();
            }
            // Ignore spaces
        }

        // Add the last number to the result
        if (num != 0) {
            result += sign * num;
        }

        return (int)result;
    }
};

Basic Calculator in TypeScript

function calculate(s: string): number {
    const stack: number[] = [];
    let result = 0;
    let num = 0;
    let sign = 1; // 1 for positive, -1 for negative

    for (let i = 0; i < s.length; i++) {
        const char = s[i];

        if (char >= '0' && char <= '9') {
            num = num * 10 + parseInt(char, 10);
        } else if (char === '+') {
            result += sign * num;
            num = 0;
            sign = 1;
        } else if (char === '-') {
            result += sign * num;
            num = 0;
            sign = -1;
        } else if (char === '(') {
            // Push the current result and sign onto the stack
            stack.push(result);
            stack.push(sign);
            // Reset for the sub-expression
            result = 0;
            sign = 1;
        } else if (char === ')') {
            result += sign * num;
            num = 0;

            // Pop the sign and result from the parent expression
            result *= stack.pop()!; // Multiply by the sign before the parenthesis
            result += stack.pop()!; // Add the result from before the parenthesis
        }
        // Ignore spaces
    }

    // Add the last number to the result
    if (num !== 0) {
        result += sign * num;
    }

    return result;
}

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.