-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathBasicCalculator.java
More file actions
32 lines (32 loc) · 1015 Bytes
/
BasicCalculator.java
File metadata and controls
32 lines (32 loc) · 1015 Bytes
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
public class Solution {
public int calculate(String s) {
Deque<Integer> nums = new ArrayDeque<>();
Deque<Integer> signs = new ArrayDeque<>();
int sign = 1;
int n = 0;
int result = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
n = n * 10 + (c - '0');
} else if (c != ' ') {
result += sign * n;
n = 0;
if (c == '+') {
sign = 1;
} else if (c == '-') {
sign = -1;
} else if (c == '(') {
nums.push(result);
signs.push(sign);
sign = 1;
result = 0;
} else if (c == ')' && !signs.isEmpty()) {
result = result * signs.pop() + nums.pop();
}
}
}
result += sign * n;
return result;
}
}