File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
src/Algorithms/0150.evaluate-reverse-polish-notation Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+
3+ /**
4+ * @param String[] $tokens
5+ * @return Integer
6+ */
7+ function evalRPN ($tokens ) {
8+ $stack = [];
9+ $conVal = 0 ;
10+ $res = 0 ;
11+
12+ if (count ($tokens )< 2 )return intval ($tokens [0 ]);
13+ foreach ($tokens as $s ){
14+ if (($s == " +" ) || ($s == " -" ) || ($s == " *" ) || ($s == " /" )){
15+ switch ($s ){
16+ case " +" : $res = array_pop ($stack )+ array_pop ($stack );
17+ array_push ($stack , $res );
18+ break ;
19+ case " -" : $x = array_pop ($stack );
20+ $y = array_pop ($stack );
21+ $res = $y - $x ;
22+ array_push ($stack , $res );
23+ break ;
24+ case " *" : $res = array_pop ($stack )* array_pop ($stack );
25+ array_push ($stack , $res );
26+ break ;
27+ case " /" : $a = array_pop ($stack );
28+ $b = array_pop ($stack );
29+ if ($b == 0 )$res = 0 ;
30+ else $res = intval ($b / $a );
31+ array_push ($stack , $res );
32+ break ;
33+ }
34+ }
35+ else {
36+ $conVal = intval ($s );
37+ array_push ($stack , $conVal );
38+ }
39+ }
40+ return $res ;
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments