Binary to Decimal
Medium · rating 1050 · Math, Strings
Read a binary string (only 0 and 1). Print its value in decimal.
Constraints: up to 60 bits.
Editorial
Binary to Decimal converts a base-2 string to its integer value — a fundamental number-base problem.
Approach (Horner's method)
Process the bits left to right, doing value = value * 2 + bit for each. This folds in every place value without ever computing powers of two explicitly.
value = 0
for ch in s:
value = value * 2 + (ord(ch) - ord('0'))
return valueComplexity
Time: O(n) in the number of bits. Space: O(1).
Related problems
- RGB to Hex Color — Easy
- GC Content — Easy
- Product of Digits — Easy
- Sum of Digits — Easy
- IP Address to Integer — Medium
- Keystroke Count — Easy