Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function polska($str) {
- $stack = new SplStack();
- foreach(explode(' ', $str) as $item) {
- if(in_array($item, array('+', '-', '*', '/'))) {
- if($stack->count() < 2 ) {
- throw new Exception("invalid count of arguments");
- }
- $arg_1 = $stack->pop();
- $arg_2 = $stack->pop();
- switch($item) {
- case '+':
- $res = $arg_1 + $arg_2;
- break;
- case '-':
- $res = $arg_1 - $arg_2;
- break;
- case '*':
- $res = $arg_1 * $arg_2;
- break;
- case '/':
- $res = $arg_1 / $arg_2;
- break;
- }
- $stack->push($res);
- } else {
- if(!is_numeric($item)) {
- throw new Exception("invalid value {$item}");
- }
- $stack->push($item);
- }
- }
- return $stack->pop();
- }
- echo polska('5 3 8 + *') . "\n";
- echo polska('5 3 + 8 *') . "\n";
- echo polska('5 *') . "\n";
Advertisement
Add Comment
Please, Sign In to add comment