Basic Calculator
Basic Calculator
Implement a basic calculator that evaluates a given mathematical expression represented as a string.
Constraints:
- The input string
swill have a length between 1 and 3 * 10^5 characters. - The string
swill only contain digits,'+','-','(',')', and spaces. - The expression represented by
sis guaranteed to be valid. - Unary plus (
+) will not be used (e.g.,+1or+(2 + 3)are invalid). - Unary minus (
-) is permitted (e.g.,-1or-(2 + 3)are valid). - There will be no consecutive operators.
- All intermediate and final results will fit within a signed 32-bit integer.
Note: You are not allowed to use any built-in functions that evaluate strings as mathematical expressions (e.g., eval()).
Examples:
-
Input:
s = "1 + 1"Output:2 -
Input:
s = " 2-1 + 2 "Output:3 -
Input:
s = "(1+(4+5+2)-3)+(6+8)"Output:23
Similar LeetCode problem: Basic Calculator
AI interview prep
Core dilemma
Parsing and evaluating a string-based arithmetic expression with nested parentheses and operator precedence, while managing state and avoiding built-in evaluation functions.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Basic Calculator
Basic Calculator
Implement a basic calculator that evaluates a given mathematical expression represented as a string.
Constraints:
- The input string
swill have a length between 1 and 3 * 10^5 characters. - The string
swill only contain digits,'+','-','(',')', and spaces. - The expression represented by
sis guaranteed to be valid. - Unary plus (
+) will not be used (e.g.,+1or+(2 + 3)are invalid). - Unary minus (
-) is permitted (e.g.,-1or-(2 + 3)are valid). - There will be no consecutive operators.
- All intermediate and final results will fit within a signed 32-bit integer.
Note: You are not allowed to use any built-in functions that evaluate strings as mathematical expressions (e.g., eval()).
Examples:
-
Input:
s = "1 + 1"Output:2 -
Input:
s = " 2-1 + 2 "Output:3 -
Input:
s = "(1+(4+5+2)-3)+(6+8)"Output:23
Similar LeetCode problem: Basic Calculator