MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Polymorphic Areas with Explanation

PHP Medium PHP OOP Basics 32 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around area, type, line. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Types: C r for circle, S a for square. Print area for each shape with 2 decimals.

Input Format

First n. Next n lines type value.

Output Format

n lines areas.

Constraints

n

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php abstract class Shape{ abstract function area(); } class Circle extends Shape{ private $r; function __construct($r){ $this->r=$r; } function area(){ return 3.141592653589793*$this->r*$this->r; } } class Square extends Shape{ private $a; function __construct($a){ $this->a=$a; } function area(){ return $this->a*$this->a; } } $inputLines=preg_split('/\\R/', rtrim(stream_get_contents(STDIN))); if(!$inputLines || trim($inputLines[0])==='') exit; $n=intval($inputLines[0]); $output=[]; for($i=1;$i<=$n;$i++){ $tokens=preg_split('/\\s+/', trim($inputLines[$i] ?? '')); $t=$tokens[0] ?? ''; $v=floatval($tokens[1] ?? 0); if($t==='C') $sh=new Circle($v); else $sh=new Square($v); $output[] = number_format($sh->area(),2,'.',''); } echo implode(PHP_EOL,$output); ?>

Output Example

Input:
3 C 1 S 2 C 3
Output:
3.14 4.00 28.27

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next