Bank Account
PHP
Easy
6 views
Problem Description
Create BankAccount with deposit/withdraw. Withdraw that goes below 0 is ignored. Print final balance.
Input Format
First line q. Next q lines: DEPOSIT x or WITHDRAW x.
Output Format
One integer balance.
Sample Test Case
Input:
4
DEPOSIT 100
WITHDRAW 30
WITHDRAW 100
DEPOSIT 10
Official Solution
<?php
class BankAccount{
private $bal=0;
function deposit($x){ $this->bal += $x; }
function withdraw($x){ if($this->bal >= $x) $this->bal -= $x; }
function balance(){ return $this->bal; }
}
$inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN)));
if(!$inputLines || trim($inputLines[0])==='') exit;
$q=intval($inputLines[0]);
$acc=new BankAccount();
for($i=1;$i<=$q;$i++){
$tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? ''), 2);
$cmd=$tokens[0] ?? '';
$x=intval($tokens[1] ?? 0);
if($cmd==='DEPOSIT') $acc->deposit($x);
elseif($cmd==='WITHDRAW') $acc->withdraw($x);
}
echo $acc->balance();
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!