Counter Object
PHP
Easy
6 views
Problem Description
Make a Counter class with inc() and dec(). Process q commands INC or DEC and print final value.
Input Format
First line q. Next q lines.
Output Format
One integer final.
Sample Test Case
Input:
5
INC
INC
DEC
INC
DEC
Official Solution
<?php
class Counter{
private $v=0;
function inc(){ $this->v++; }
function dec(){ $this->v--; }
function get(){ return $this->v; }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$c=new Counter();
for($i=1;$i<=$q;$i++){
$cmd=trim($inputLines[$i] ?? '');
if($cmd==='INC') $c->inc();
elseif($cmd==='DEC') $c->dec();
}
echo $c->get();
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!