Evaluate Left-to-Right
PHP
Hard
4 views
Problem Description
Expression tokens like: number op number op number. Evaluate strictly left-to-right (no precedence). Ops are + - *.
Input Format
One line tokens separated by spaces.
Output Format
One integer result.
Official Solution
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$t=preg_split('/\\s+/', $inputText);
$acc=intval($t[0] ?? 0);
for($i=1;$i+1<count($t);$i+=2){
$op=$t[$i];
$b=intval($t[$i+1]);
if($op==='+') $acc+=$b;
elseif($op==='-') $acc-=$b;
else $acc*=$b;
}
echo $acc;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!