Postfix with Error Handling

Postfix with Error Handling

Hard PHP PHP Error Handling 28 views
Explanation Complexity

Problem Statement

Evaluate postfix expression. If it ever divides by zero or lacks operands, print ERROR.

Input Format

One line tokens.

Output Format

Result or ERROR.

Example

6 0 /
ERROR

Constraints

Token count

Input / Output Format

Input Format
One line tokens.
Output Format
Result or ERROR.
Constraints
Token count

Examples

Input:
6 0 /
Output:
ERROR

Example Solution (Public)

PHP
<?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]);
?>

Official Solution Code

<?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]);
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.