File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments