Command Calculator
PHP
Hard
4 views
Problem Description
Start value=0. Commands: ADD x, SUB x, MUL x, DIV x (integer, ignore if x=0). Print final value.
Input Format
First line q. Next q lines commands.
Output Format
One integer final value.
Sample Test Case
Input:
5
ADD 10
MUL 3
SUB 4
DIV 2
DIV 0
Official Solution
<?php
$inputLines=preg_split('/\\R/', trim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$val=0;
for($i=1;$i<=$q;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 2);
$cmd=$tokens[0] ?? '';
$x=intval($tokens[1] ?? 0);
if($cmd==='ADD') $val+=$x;
elseif($cmd==='SUB') $val-=$x;
elseif($cmd==='MUL') $val*=$x;
elseif($cmd==='DIV'){
if($x!==0) $val=intdiv($val,$x);
}
}
echo $val;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!