Big Decimal to Binary
PHP
Hard
6 views
Problem Description
You get a big decimal integer as string. Convert it to binary.
Input Format
One line: n (decimal, non-negative).
Output Format
One binary string.
Official Solution
<?php
$n=trim(stream_get_contents(STDIN));
if($n==='') exit;
$n=ltrim($n,'0');
if($n===''){ echo '0'; exit; }
$out='';
while($n!=='0'){
$carry=0; $next='';
for($i=0,$len=strlen($n);$i<$len;$i++){
$cur=$carry*10 + (ord($n[$i])-48);
$q=intdiv($cur,2);
$carry=$cur%2;
if(!($next==='' && $q===0)) $next.=chr($q+48);
}
$out=($carry?'1':'0').$out;
$n=($next===''?'0':$next);
}
echo $out;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!