Base Conversion with Validation
PHP
Hard
5 views
Problem Description
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.
Official Solution
<?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);
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!