Skip to content

Commit e899272

Browse files
author
Prakhar Agarwal
authored
Create Basic Calculator 2.java
1 parent 0e3ddd1 commit e899272

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Basic Calculator 2.java

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
import java.util.Stack;
4+
5+
class Solution {
6+
public int calculate(String s) {
7+
return solvePostFix(postFix(s));
8+
}
9+
10+
private int solvePostFix(List<Object> list) {
11+
Stack<Integer> st = new Stack();
12+
for (Object o : list) {
13+
if (o instanceof Integer) {
14+
st.push((Integer) o);
15+
} else {
16+
char ch = (Character) o;
17+
int b = st.pop();
18+
int a = st.pop();
19+
if (ch == '+') {
20+
st.push(a + b);
21+
} else if (ch == '-') {
22+
st.push(a - b);
23+
} else if (ch == '*') {
24+
st.push(a * b);
25+
} else if (ch == '/') {
26+
st.push(a / b);
27+
}
28+
}
29+
}
30+
return st.pop();
31+
}
32+
33+
private List<Object> postFix(String s) {
34+
List<Object> list = new ArrayList();
35+
Stack<Character> st = new Stack();
36+
int num = 0;
37+
for (char ch : s.toCharArray()) {
38+
if (ch == ' ')
39+
continue;
40+
if (Character.isDigit(ch)) {
41+
num = num * 10 + (ch - '0');
42+
} else {
43+
list.add(num);
44+
num = 0;
45+
while (!st.isEmpty() && prec(st.peek()) >= prec(ch)) {
46+
list.add(st.pop());
47+
}
48+
st.push(ch);
49+
}
50+
}
51+
list.add(num);
52+
while (!st.isEmpty()) {
53+
list.add(st.pop());
54+
}
55+
return list;
56+
}
57+
58+
private int prec(char ch) {
59+
switch (ch) {
60+
case '+':
61+
case '-':
62+
return 1;
63+
case '*':
64+
case '/':
65+
return 2;
66+
case '^':
67+
return 3;
68+
}
69+
return -1;
70+
}
71+
}

0 commit comments

Comments
 (0)