-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBasic_Calculator.java
More file actions
34 lines (31 loc) · 1.01 KB
/
Basic_Calculator.java
File metadata and controls
34 lines (31 loc) · 1.01 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
package stack;
import java.util.Stack;
public class Basic_Calculator {
public int calculate(String s) {
Stack<Integer> st = new Stack<Integer>();
int res = 0, sign = 1;
for(int i = 0; i < s.length(); ++i){
if(Character.isDigit(s.charAt(i))){
int sum = s.charAt(i) - '0';
while(i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))){
sum = sum * 10 + s.charAt(i + 1) - '0';
++i;
}
res += sign * sum;
}else if(s.charAt(i) == '+'){
sign = 1;
}else if(s.charAt(i) == '-'){
sign = -1;
}else if(s.charAt(i) == '('){
st.push(res);
st.push(sign);
res = 0;
sign = 1;
}else if(s.charAt(i) == ')'){
res *= st.pop();
res += st.pop();
}
}
return res;
}
}