224. Basic Calculator
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = “1 + 1”
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = “(1+(4+5+2)-3)+(6+8)”
Output: 23
Constraints:
- 1 < = s . l e n g t h < = 3 ∗ 1 0 5 1 <= s.length <= 3 * 10^5 1<=s.length<=3∗105
- s consists of digits, ‘+’, ‘-’, ‘(’, ‘)’, and ’ '.
- s represents a valid expression.
- ‘+’ is not used as a unary operation (i.e., “+1” and “+(2 + 3)” is invalid).
- ‘-’ could be used as a unary operation (i.e., “-1” and “-(2 + 3)” is valid).
- There will be no two consecutive operators in the input.
- Every number and running calculation will fit in a signed 32-bit integer.
From: LeetCode
Link: 224. Basic Calculator
Solution:
Ideas:
- Convert the string into a list of tokens (numbers, ‘+’, ‘-’, ‘(’, and ‘)’). This step helps us to deal with numbers that have more than one digit.
- Use a stack to evaluate the expression.
- Whenever we see a number, we push it onto the stack.
- Whenever we see an operator (+ or -), we push it onto the stack.
- Whenever we see an opening parenthesis, we simply push it onto the stack.
- Whenever we see a closing parenthesis, we pop elements from the stack until we see the matching opening parenthesis, and evaluate the expression inside the parentheses.
- Continue processing the tokens until there are no more tokens left.
- After processing all tokens, the stack will contain the final result.
Code:
int calculate(char * s) {
int *stack = (int *)malloc(sizeof(int) * strlen(s));
int top = -1;
int operand = 0;
int result = 0; // For the on-going result
int sign = 1; // 1 means positive, -1 means negative
for (int i = 0; s[i] != '\0'; ++i) {
char ch = s[i];
if (isdigit(ch)) {
// Forming operand, since it could be more than one digit
operand = (operand * 10) + (ch - '0');
} else if (ch == '+') {
// Evaluate the expression to the left, with result, sign, operand
result += sign * operand;
// Save the recently encountered '+' sign
sign = 1;
// Reset operand
operand = 0;
} else if (ch == '-') {
result += sign * operand;
sign = -1;
operand = 0;
} else if (ch == '(') {
// Push the result and sign onto the stack, for later
// We push the result first, then sign
stack[++top] = result;
stack[++top] = sign;
// Reset operand and result, as if new evaluation begins for the new sub-expression
sign = 1;
result = 0;
} else if (ch == ')') {
// Evaluate the expression to the left
// with result, sign and operand
result += sign * operand;
// ')' marks end of expression within a set of parenthesis
// Its result is multiplied with sign on top of stack
// as stack.pop() is the sign before the parenthesis
result *= stack[top--];
// Then add to the next operand on the top.
// as stack.pop() is the result calculated before this parenthesis
result += stack[top--];
// Reset the operand
operand = 0;
}
}
return result + (sign * operand);
}