MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Base Conversion with Validation with Explanation

PHP Hard PHP Error Handling 32 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around base, invalid, decimal. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Given base b and string s, convert to decimal. If s contains invalid digit for base, print INVALID.

Input Format

One line: b s.

Output Format

Decimal or INVALID.

Constraints

2

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?php $inputText=trim(stream_get_contents(STDIN)); if($inputText==='') exit; [$b,$s]=preg_split('/\\s+/', $inputText, 2); $base=intval($b); $s=strtoupper(trim($s)); $val=0; for($i=0,$n=strlen($s);$i<$n;$i++){ $ch=$s[$i]; if($ch>='0' && $ch<='9') $d=ord($ch)-48; elseif($ch>='A' && $ch<='Z') $d=ord($ch)-55; else{ echo 'INVALID'; exit; } if($d<0 || $d>=$base){ echo 'INVALID'; exit; } $val=$val*$base + $d; } echo strval($val); ?>

Output Example

Input:
2 102
Output:
INVALID

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