Basic Calculator III

Asked atGoldman Sachs
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, '+', '-', '*', '/' operators, and open '(' and closing parentheses ')'. 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^31, 2^31 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Input: s = "1+1" Output: 2

Input: s = "6-4/2" Output: 4

Input: s = "2*(5+5*2)/3+(6/2+8)"

1 <= s <= 104 s consists of digits, '+', '-', '*', '/', '(', and ')'. s is a valid expression.

cpp

class Solution {

public:
    int calculate(string s) {
        //User Code goes here
    }
};

java

class Solution {
    public int calculate(String s) {
        // User Code goes here
        return 0;
    }
}

python

class Solution:
    def calculate(self, s: str) -> int:
        # User Code goes here
        return 0

javascript

class Solution {
    calculate(s) {
        // User Code goes here
        return 0;
    }
}

csharp

public class Solution {
    public int Calculate(string s) {
        //User Code goes here
    }
};

go

func calculate(s string) int { }
Stuck? Show a way to structure it+
  1. 01Define integer-division behavior and whitespace handling
  2. 02Scan digits into complete numbers
  3. 03Recurse for parenthesized subexpressions
  4. 04Apply operators with precedence and return at closing parenthesis

Reference answer

Then expect these follow-ups

  • How would you support exponentiation?

    Tests: follow-up reasoning

  • How do you report malformed expressions?

    Tests: follow-up reasoning

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question