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.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.
Accepted279,472Submissions694,573
Basic Calculator Solutions
✅Time: O(n)
✅Space: O(n)
C++
class Solution {
public:
int calculate(string s) {
int ans = 0;
int num = 0;
int sign = 1;
stack<int> stack{{sign}}; // stack.top(): current env's sign
for (const char c : s)
if (isdigit(c))
num = num * 10 + (c - '0');
else if (c == '(')
stack.push(sign);
else if (c == ')')
stack.pop();
else if (c == '+' || c == '-') {
ans += sign * num;
sign = (c == '+' ? 1 : -1) * stack.top();
num = 0;
}
return ans + sign * num;
}
};
Java
class Solution {
public int calculate(String s) {
int ans = 0;
int num = 0;
int sign = 1;
Deque<Integer> stack = new ArrayDeque<>(); // stack.peek(): current env's sign
stack.push(sign);
for (final char c : s.toCharArray())
if (Character.isDigit(c))
num = num * 10 + (c - '0');
else if (c == '(')
stack.push(sign);
else if (c == ')')
stack.pop();
else if (c == '+' || c == '-') {
ans += sign * num;
sign = (c == '+' ? 1 : -1) * stack.peek();
num = 0;
}
return ans + sign * num;
}
}
Python
class Solution:
def calculate(self, s: str) -> int:
ans = 0
num = 0
sign = 1
stack = [sign] # stack[-1]: current env's sign
for c in s:
if c.isdigit():
num = num * 10 + (ord(c) - ord('0'))
elif c == '(':
stack.append(sign)
elif c == ')':
stack.pop()
elif c == '+' or c == '-':
ans += sign * num
sign = (1 if c == '+' else -1) * stack[-1]
num = 0
return ans + sign * num
Watch Tutorial
Checkout more Solutions here