Basic Calculator Medium · Topics · Company Tags · Hints
Implement a calculator that evaluates a string containing a mathematical expression. The expression consists of non-negative integers and the operators +, -, *, /, as well as parentheses ( and ). The entire string represents a valid expression, and division between two integers should truncate toward zero (i.e., round down for positive results, effectively dropping the fractional part).
Input Format: A single line containing the expression string.
Output Format: The integer result of evaluating the expression.
Example 1:
Input: "3 + 2 * 2"
Output: 7
Explanation: Multiplication has higher precedence, so we compute 2 * 2 = 4 first, then add 3 to get 7.
Example 2:
Input: "10 / 3 + 1"
Output: 4
Explanation: 10 / 3 truncates to 3, plus 1 yields 4.
Example 3:
Input: "(8 - 3) * (4 + 6) / 2"
Output: 25
Explanation: 8 - 3 = 5, 4 + 6 = 10, multiply to get 50, then divide by 2 for a final result of 25.
Constraints:
1 <= expression.length <= 10,0000-9, the operators +, -, *, /, parentheses ( and ), and optional spaces.