
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.
- Parse the expression "1 + 1".
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.
- Parse the expression "2-1 + 2" (ignoring spaces).
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)
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 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