Basic Calculator

Hard#224evaluate

You get a correct expression as a string: non-negative integers, + and −, brackets and spaces; a minus may also stand before a number or a bracket on its own. Work out its value without any built-in eval. Our example: "12-(3-(4+1))+2" — the answer is 16.

input
s: an expression of non-negative integers, +, -, parentheses and spaces. - may also be unary, at the start or right after (: -(2 + 3); + may not.
returns
The value of s. No eval or the like: the point is to compute it yourself.
constraints
  • 1 ≤ s.length ≤ 10⁴
  • s: digits, + - ( ) and spaces
  • s is a valid expression, with no two operators in a row
  • every number and every result along the way fit in a 32-bit integer
our 16 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} s
 * @return {number}
 */
function calculate(s) {

}
Ctrl ↵
format
reset

saved in this browser

16 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more stack problems

Pattern “Stack” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.