
Problem
Solution
Submissions
Calculator with Parentheses
Certification: Intermediate Level
Accuracy: 25%
Submissions: 4
Points: 8
Write a C# function that evaluates mathematical expressions with parentheses and basic operators (+, -, *, /). The function should handle parentheses for operation precedence, multiplication and division (equal precedence), addition and subtraction (equal precedence), proper operator precedence, negative numbers, and spaces in the expression.
Example 1
- Input: s = "3 + 5 * 2"
- Output: 13
- Explanation:
- Step 1: Parse the expression, identifying numbers and operators.
- Step 2: Apply operator precedence rules (multiplication before addition).
- Step 3: Calculate 5 * 2 = 10.
- Step 4: Calculate 3 + 10 = 13.
- Step 5: Return the final result 13.
Example 2
- Input: s = "(4 + 2) * 3 - 6 / 2"
- Output: 15
- Explanation:
- Step 1: Evaluate the parenthesized expression (4 + 2) = 6.
- Step 2: Apply multiplication operation: 6 * 3 = 18.
- Step 3: Apply division operation: 6 / 2 = 3.
- Step 4: Apply subtraction: 18 - 3 = 15.
- Step 5: Return the final result 15.
Constraints
- 1 ≤ s.length ≤ 100
- s consists of digits (0-9), '+', '-', '*', '/', '(', ')', and spaces
- The expression is valid and can be evaluated to a 32-bit integer
- Time Complexity: O(n) where n is the length of the expression
- Space Complexity: O(n) for storing intermediate results and operands
Editorial
My Submissions
All Solutions
| Lang | Status | Date | Code |
|---|---|---|---|
| You do not have any submissions for this problem. | |||
| User | Lang | Status | Date | Code |
|---|---|---|---|---|
| No submissions found. | ||||
Solution Hints
- Use two stacks: one for numbers and one for operators
- Process the expression from left to right
- Handle parentheses by using recursion or stack operations
- Consider operator precedence when evaluating operations
- Use a helper function to perform calculations based on operators