Tutorialspoint
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
NumberStackGoldman SachsSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Parse the expression from left to right, handling numbers and operators.
 Step 2: Use stacks to manage the order of operations and handle parentheses.
 Step 3: Implement operator precedence (* and / have higher precedence than + and -).
 Step 4: Process opening parentheses by pushing onto stack, and closing parentheses by computing the enclosed expression.
 Step 5: After processing the entire expression, apply any remaining operations in the stack.

Submitted Code :