marrtins

Reverse Polish notation PHP implementation

Jan 1st, 2021 (edited)
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.60 KB | None | 0 0
  1. function rpn($expr){
  2.     if(is_string($expr)){
  3.         $expr = explode(" ", $expr);
  4.     }
  5.  
  6.     $stack = [];
  7.     foreach($expr as $e){
  8.         if(is_numeric($e)){
  9.             $stack[] = $e;
  10.         } else {
  11.             $n1 = array_pop($stack);
  12.             $n2 = array_pop($stack);
  13.             $result = null;
  14.             if($e == "+"){
  15.                 $result = $n2 + $n1;
  16.             } elseif($e == "*"){
  17.                 $result = $n2 * $n1;
  18.             } elseif($e == "-"){
  19.                 $result = $n2 - $n1;
  20.             } elseif($e == "/"){
  21.                 $result = $n2 / $n1;
  22.             }
  23.             array_push($stack, $result);
  24.         }
  25.     }
  26.  
  27.     if(count($stack) != 1){
  28.         throw new TypeError("Invalid rpn expression");
  29.     }
  30.  
  31.     return array_pop($stack);
  32. }
  33.  
Add Comment
Please, Sign In to add comment