Evaluate Postfix Expression

Evaluate Postfix Expression

Hard PHP PHP Functions 29 views
Explanation Complexity

Problem Statement

Given a postfix expression with integers and ops + - * /, evaluate it using helper functions.

Input Format

One line tokens.

Output Format

One integer result.

Example

10 3 - 2 *
14

Constraints

Token count

Input / Output Format

Input Format
One line tokens.
Output Format
One integer result.
Constraints
Token count

Examples

Input:
10 3 - 2 *
Output:
14

Example Solution (Public)

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

Official Solution Code

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

                                        
Please login to submit solutions.