File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed
solution/0227.Basic Calculator II Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int calculate (String s ) {
3
+ char [] cs = s .toCharArray ();
4
+ Deque <Character > op = new ArrayDeque <>();
5
+ Deque <Integer > num = new ArrayDeque <>();
6
+ for (int i = 0 ; i < cs .length ; ++i ) {
7
+ if (cs [i ] == '*' || cs [i ] == '/' ) {
8
+ op .push (cs [i ]);
9
+ } else if (cs [i ] == '+' || cs [i ] == '-' ) {
10
+ if (!op .isEmpty ()) {
11
+ calc (op , num );
12
+ }
13
+ op .push (cs [i ]);
14
+ } else if (Character .isDigit (cs [i ])) {
15
+ int j = i ;
16
+ int k = 0 ;
17
+ while (j < cs .length && Character .isDigit (cs [j ])) {
18
+ k = k * 10 + cs [j ] - '0' ;
19
+ ++j ;
20
+ }
21
+ i = j - 1 ;
22
+ num .push (k );
23
+ if (!op .isEmpty () && (op .peek () == '*' || op .peek () == '/' )) {
24
+ calc (op , num );
25
+ }
26
+ }
27
+ }
28
+ while (!op .isEmpty ()) {
29
+ calc (op , num );
30
+ }
31
+ return num .peek ();
32
+ }
33
+
34
+ private void calc (Deque <Character > op , Deque <Integer > num ) {
35
+ int y = num .pop ();
36
+ int x = num .pop ();
37
+ switch (op .pop ()) {
38
+ case '*' :
39
+ num .push (x * y );
40
+ break ;
41
+ case '/' :
42
+ num .push (x / y );
43
+ break ;
44
+ case '+' :
45
+ num .push (x + y );
46
+ break ;
47
+ default :
48
+ num .push (x - y );
49
+ break ;
50
+ }
51
+ }
52
+ }
You can’t perform that action at this time.
0 commit comments