MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

PHP Program to Big Binary to Decimal with Explanation

PHP Hard PHP Data Types 24 views
This problem helps you practice core PHP fundamentals in a practical way. It builds intuition around decimal, binary, one. Let’s break it down step by step so you can implement it confidently.
Back to Questions

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.

Constraints

1

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
<?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; ?>

Output Example

Input:
10101
Output:
21

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next