-
Notifications
You must be signed in to change notification settings - Fork 0
/
224. Basic Calculator
38 lines (34 loc) · 1.47 KB
/
224. Basic Calculator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
https://leetcode.com/problems/basic-calculator/description/
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .
You may assume that the given expression is always valid.
*/
public class Solution {
private static final Logger logger = LogManager.getLogger(Solution.class);
public int calculate(String s) {
int length = s.length();
ArrayDeque<Integer> stack = new ArrayDeque<>();
stack.push(0);
for (int i = 0, sign = 1; i < length; i++) {
if (Character.isDigit(s.charAt(i))) {
int num = Integer.parseInt(String.valueOf(s.charAt(i)));
for (; i < length - 1 && Character.isDigit(s.charAt(i + 1)); i++) {
num = num * 10 + Integer.parseInt(String.valueOf(s.charAt(i + 1)));
}
stack.push(stack.pop() + sign * num);
} else if (s.charAt(i) == '+') {
sign = 1;
} else if (s.charAt(i) == '-') {
sign = -1;
} else if (s.charAt(i) == '(') {
stack.push(sign);
stack.push(0);
sign = 1;
} else if (s.charAt(i) == ')') { // Update last sum = current sum * sign
stack.push(stack.pop() * stack.pop() + stack.pop());
}
}
return stack.pop();
}
}