Big Binary to Decimal

Big Binary to Decimal

Hard PHP PHP Data Types 25 views
Explanation Complexity

Problem Statement

Convert a binary string (up to 500 bits) into a decimal string.

Input Format

One token b (0/1).

Output Format

One decimal string.

Example

10101
21

Constraints

1

Input / Output Format

Input Format
One token b (0/1).
Output Format
One decimal string.
Constraints
1

Examples

Input:
10101
Output:
21

Example Solution (Public)

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

Official Solution Code

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

                                        
Please login to submit solutions.