Base-N to Decimal
PHP
Medium
5 views
Problem Description
Given base b (2..36) and string s (digits/letters), convert to decimal.
Input Format
One line: b s.
Output Format
One integer.
Constraints
s fits in 64-bit when converted.
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;
else $d=ord($ch)-55;
$val=$val*$base + $d;
}
echo $val;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!