Guest User

Untitled

a guest
Apr 20th, 2012
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.81 KB | None | 0 0
  1. function polska($str) {
  2.     $stack = new SplStack();
  3.     foreach(explode(' ', $str) as $item) {
  4.         if(in_array($item, array('+', '-', '*', '/'))) {
  5.             if($stack->count() < 2 ) {
  6.                 throw new Exception("invalid count of arguments");
  7.             }
  8.             $arg_1 = $stack->pop();
  9.             $arg_2 = $stack->pop();
  10.             switch($item) {
  11.                 case '+':
  12.                     $res = $arg_1 + $arg_2;
  13.                     break;
  14.                 case '-':
  15.                     $res = $arg_1 - $arg_2;
  16.                     break;
  17.                 case '*':
  18.                     $res = $arg_1 * $arg_2;
  19.                     break;
  20.                 case '/':
  21.                     $res = $arg_1 / $arg_2;
  22.                     break;
  23.             }
  24.             $stack->push($res);
  25.         } else {
  26.             if(!is_numeric($item)) {
  27.                 throw new Exception("invalid value {$item}");
  28.             }
  29.             $stack->push($item);
  30.         }
  31.     }
  32.     return $stack->pop();
  33. }
  34.  
  35. echo polska('5 3 8 + *') . "\n";
  36. echo polska('5 3 + 8 *') . "\n";
  37. echo polska('5 *') . "\n";
Advertisement
Add Comment
Please, Sign In to add comment