Big Binary to Decimal
PHP
Hard
6 views
Problem Description
Convert a binary string (up to 500 bits) into a decimal string.
Input Format
One token b (0/1).
Output Format
One decimal string.
Official Solution
<?php
$b=trim(stream_get_contents(STDIN));
if($b==='') exit;
$dec='0';
for($i=0,$n=strlen($b);$i<$n;$i++){
$carry=0; $next='';
for($j=strlen($dec)-1;$j>=0;$j--){
$v=(ord($dec[$j])-48)*2 + $carry;
$next=chr(($v%10)+48).$next;
$carry=intdiv($v,10);
}
if($carry) $next=chr($carry+48).$next;
$dec=ltrim($next,'0'); if($dec==='') $dec='0';
if($b[$i]==='1'){
$k=strlen($dec)-1; $carry=1; $next='';
while($k>=0 || $carry){
$d=($k>=0)?(ord($dec[$k])-48):0;
$s=$d+$carry;
$next=chr(($s%10)+48).$next;
$carry=intdiv($s,10);
$k--;
}
$pref=substr($dec,0,strlen($dec)-strlen($next));
$dec=ltrim($pref.$next,'0'); if($dec==='') $dec='0';
}
}
echo $dec;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!