Skip to content

Commit b4abac8

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 227_Basic_Calculator_II.java
1 parent b862509 commit b4abac8

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Strings/227_Basic_Calculator_II.java

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
class Solution {
2+
public int calculate(String s) {
3+
if (s == null || s.length() == 0) {
4+
return 0;
5+
}
6+
7+
Stack<Integer> st = new Stack<>();
8+
int num = 0, total = 0;
9+
char sign = '+';
10+
11+
for (int i = 0; i < s.length(); i++) {
12+
char c = s.charAt(i);
13+
14+
if (Character.isDigit(c)) {
15+
num = num * 10 + c - '0';
16+
}
17+
18+
if (i == s.length() - 1 || !Character.isDigit(c) && c != ' ') {
19+
switch (sign) {
20+
case '+':
21+
st.push(num);
22+
break;
23+
case '-':
24+
st.push(-num);
25+
break;
26+
case '*':
27+
st.push(st.pop() * num);
28+
break;
29+
case '/':
30+
st.push(st.pop() / num);
31+
break;
32+
}
33+
34+
sign = c;
35+
num = 0;
36+
}
37+
}
38+
39+
while (!st.isEmpty()) {
40+
total += st.pop();
41+
}
42+
return total;
43+
}
44+
}

0 commit comments

Comments
 (0)