224 Basic Calculator
224. Basic Calculator
1. Question
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 232. Implementation
3. Time & Space Complexity
Last updated
"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23Last updated
class Solution {
public int calculate(String s) {
int res = 0;
int num = 0, sign = 1;
Stack<Integer> stack = new Stack<>();
stack.push(sign);
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
num = 10 * num + (c - '0');
}
else if (c == '+' || c == '-') {
res += sign * num;
sign = stack.peek() * (c == '+' ? 1 : -1);
num = 0;
}
else if (c == '(') {
stack.push(sign);
}
else if (c == ')') {
stack.pop();
}
}
res += sign * num;
return res;
}
}