Binary to Decimal - Problem

Given a binary number as a string, convert it to its decimal equivalent without using any built-in conversion functions.

A binary number consists of only 0 and 1 digits. Each digit represents a power of 2, starting from the rightmost digit as 2⁰.

Example: Binary "1101" = 1×2³ + 1×2² + 0×2¹ + 1×2⁰ = 8 + 4 + 0 + 1 = 13

Input & Output

Example 1 — Basic Binary
$ Input: binary = "1101"
Output: 13
💡 Note: 1×2³ + 1×2² + 0×2¹ + 1×2⁰ = 8 + 4 + 0 + 1 = 13
Example 2 — Single Bit
$ Input: binary = "1"
Output: 1
💡 Note: Single bit 1 in position 0: 1×2⁰ = 1
Example 3 — All Zeros
$ Input: binary = "000"
Output: 0
💡 Note: All bits are 0, so the decimal value is 0

Constraints

  • 1 ≤ binary.length ≤ 30
  • binary consists of only '0' and '1' characters

Visualization

Tap to expand
INPUTALGORITHMRESULTBinary String1101Binary: "1101"1Start: result = 02Process each bit left-to-right3result = result × 2 + bit4Return final result0→1→3→6→1313Decimal ValueKey Insight:Doubling the running sum and adding each bit naturally builds the decimal value in one passTutorialsPoint - Binary to Decimal | Left-to-Right Doubling
Asked in
Google 25 Microsoft 20 Amazon 18
27.2K Views
Medium Frequency
~8 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen