Basic Calculator III
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 0javascript
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+
- 01Define integer-division behavior and whitespace handling
- 02Scan digits into complete numbers
- 03Recurse for parenthesized subexpressions
- 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.

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
Next question