Tutorialspoint
Problem
Solution
Submissions

Basic Calculator

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to implement a basic calculator that evaluates a string expression containing non-negative integers, '+', '-', '(' and ')' operators. The expression is guaranteed to be valid and there are no leading zeros in the numbers. Spaces in the expression should be ignored.

Example 1
  • Input: s = "1 + 1"
  • Output: 2
  • Explanation:
    • Parse the expression "1 + 1".
    • Perform addition: 1 + 1 = 2.
    • Therefore, the result is 2.
Example 2
  • Input: s = " 2-1 + 2 "
  • Output: 3
  • Explanation:
    • Parse the expression "2-1 + 2" (ignoring spaces).
    • Perform operations left to right: 2 - 1 = 1, then 1 + 2 = 3.
    • Therefore, the result is 3.
Constraints
  • 1 ≤ s.length ≤ 3 * 10^5
  • s consists of digits, '+', '-', '(', ')', and ' '
  • s represents a valid expression
  • '+' is not used as a unary operation
  • '-' could be used as a unary operation but only at the beginning or after '('
  • Time Complexity: O(n)
  • Space Complexity: O(n)
NumberStackCognizantShopify
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 a stack to handle parentheses and maintain intermediate results
  • Keep track of the current number being parsed and the operation to perform
  • When encountering '+' or '-', apply the previous operation and update the operator
  • When encountering '(', push current result and operator to stack
  • When encountering ')', pop from stack and combine with current result
  • Handle spaces by simply ignoring them during parsing

Steps to solve by this approach:

 Step 1: Initialize a stack, result variable, current number, and sign tracker
 Step 2: Iterate through each character in the input string
 Step 3: If digit, build the current number by multiplying by 10 and adding digit
 Step 4: If '+' or '-', add signed number to result, reset number, update sign
 Step 5: If '(', push current result and sign to stack, reset for sub-expression
 Step 6: If ')', complete current sub-expression, pop and combine with previous result
 Step 7: After parsing, add the final number to result and return

Submitted Code :