Basic Calculator

Hard

Basic Calculator

Problem Statement

Given a string

s
representing a mathematical expression with parentheses, create a function to evaluate the expression and return the result as a number.

The valid operators in the expression are

+
,
-
,
*
, and
/
. The expression may contain multiple spaces between operators and operands. The expression may also contain nested parentheses.

Your function should support non-negative integers and decimal numbers.

Rules and Constraints

  • The input string
    s
    will only contain digits,
    +
    ,
    -
    ,
    *
    ,
    /
    , and parentheses. There will be at most one
    +
    ,
    -
    ,
    *
    , or
    /
    operator between each operand.
  • The input string
    s
    is guaranteed to contain at least one operand and at most one
    +
    or
    -
    operator.
  • There will not be any division by zero in the input string
    s
    .
  • The input string
    s
    will not contain any invalid expressions that would cause a stack overflow.
  • Your function should return a non-negative number as the result.

Output

Your function should return the result of the mathematical expression as a number. The result may be a decimal number if the input expression contains decimal points.

Example

Input: {"s":"1 + 1"} Output: 2

CompaniesGoogle
JavaScript

Login to write code

Solve problems, verify your skills, and earn XP.