Postfix with Error Handling
PHP
Hard
5 views
Problem Description
Evaluate postfix expression. If it ever divides by zero or lacks operands, print ERROR.
Input Format
One line tokens.
Output Format
Result or ERROR.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tok=preg_split('/\\s+/', $inputText);
$st=[];
foreach($tok as $t){
if($t==='') continue;
if($t==='+'||$t==='-'||$t==='*'||$t==='/'){
if(count($st)<2){ echo 'ERROR'; exit; }
$b=array_pop($st);
$a=array_pop($st);
if($t==='/' && $b===0){ echo 'ERROR'; exit; }
if($t==='+') $st[]=$a+$b;
elseif($t==='-') $st[]=$a-$b;
elseif($t==='*') $st[]=$a*$b;
else $st[]=intdiv($a,$b);
}else{
if(!preg_match('/^[+-]?[0-9]+$/',$t)){ echo 'ERROR'; exit; }
$st[] = intval($t);
}
}
if(count($st)!==1) echo 'ERROR';
else echo strval($st[0]);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!