forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasicCalculatorII.java
43 lines (37 loc) · 1.09 KB
/
BasicCalculatorII.java
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
41
42
43
class BasicCalculatorII {
// TC => O(n), Space O(n)
public int calculate(String s) {
Stack<Integer> st = new Stack<>();
char prevSign = '+';
int no = 0;
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
if(Character.isDigit(c)){
no = no*10 + (c-'0');
}
if(isOperator(c) || i ==s.length()-1){
if(prevSign == '+'){
st.push(no);
} else if(prevSign == '-'){
st.push(-no);
} else if(prevSign =='*'){
int top = st.pop();
st.push(top * no);
} else if(prevSign =='/'){
int top = st.pop();
st.push(top/no);
}
no =0;
prevSign =c;
}
}
int res = 0;
while(!st.empty()){ // 1+2+3+4
res += st.pop();
}
return res;
}
private boolean isOperator(char c){
return c=='+' || c=='-'|| c=='/' || c=='*';
}
}