-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBasicCalculator.java
More file actions
40 lines (40 loc) · 1.09 KB
/
BasicCalculator.java
File metadata and controls
40 lines (40 loc) · 1.09 KB
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
39
40
public class Solution {
public int calculate(String s) {
int len = s.length();
if (len == 0) {
return 0;
}
int num = 0;
int sign = 1;
int result = 0;
Stack<Integer> st = new Stack<>();
for (int i = 0; i < len; ++i) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (int) (c - '0');
} else if (c == '+') {
result += sign * num;
sign = 1;
num = 0;
} else if (c == '-') {
result += sign * num;
sign = -1;
num = 0;
} else if (c == '(') {
st.push(result);
st.push(sign);
sign = 1;
result = 0;
} else if (c == ')') {
result += sign * num;
num = 0;
result *= st.pop();
result += st.pop();
}
}
if (num != 0) {
result += sign * num;
}
return result;
}
}