Binary to Decimal
PHP
Medium
4 views
Problem Description
Convert a binary string to decimal.
Input Format
One token b (only 0/1).
Output Format
One integer.
Official Solution
<?php
$b=trim(stream_get_contents(STDIN));
if($b==='') exit;
$ans=0;
for($i=0,$n=strlen($b);$i<$n;$i++){
$ans=$ans*2 + ($b[$i]==='1'?1:0);
}
echo $ans;
?>
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!