forked from singlemancombat/interview-preparation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasicCaculator.java
More file actions
37 lines (31 loc) · 778 Bytes
/
Copy pathBasicCaculator.java
File metadata and controls
37 lines (31 loc) · 778 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
33
34
35
36
37
public class Solution {
public static int calculate(String s) {
int len = s.length();
int sign = 1;
int result = 0;
char[] chars = s.toCharArray();
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 0; i < len; i++) {
if (chars[i] == '+') {
sign = 1;
} else if (chars[i] == '-') {
sign = -1;
} else if (Character.isDigit(chars[i])) {
int sum = s.charAt(i) - '0';
while (i + 1 < len && Character.isDigit(chars[i + 1])) {
sum = sum * 10 + (chars[i + 1] - '0');
i++;
}
result += sum * sign;
} else if (chars[i] == '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (chars[i] == ')') {
result = result * stack.pop() + stack.pop();
}
}
return result;
}
}