Base Conversion with Validation

Base Conversion with Validation

Hard PHP PHP Error Handling 33 views
Explanation Complexity

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.

Example

2 102
INVALID

Constraints

2

Input / Output Format

Input Format
One line: b s.
Output Format
Decimal or INVALID.
Constraints
2

Examples

Input:
2 102
Output:
INVALID

Example Solution (Public)

PHP
<?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);
?>

Official Solution Code

<?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);
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.