Evaluate Postfix Expression
PHP
Hard
9 views
Problem Description
Given a postfix expression with integers and ops + - * /, evaluate it using helper functions.
Input Format
One line tokens.
Output Format
One integer result.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tok=preg_split('/\\s+/', $inputText);
function applyOp($a,$b,$op){
if($op==='+') return $a+$b;
if($op==='-') return $a-$b;
if($op==='*') return $a*$b;
return intdiv($a,$b);
}
$st=[];
foreach($tok as $t){
if($t==='') continue;
if($t==='+'||$t==='-'||$t==='*'||$t==='/'){
$b=array_pop($st); $a=array_pop($st);
$st[] = applyOp($a,$b,$t);
}else $st[] = intval($t);
}
echo strval($st[count($st)-1] ?? 0);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!