Binary to Octal conversion
Detailed guide and Python implementation for the 'Binary to Octal conversion' problem.
Problem Statement
Write a function binary_to_octal(binary_str) that takes a string representing a binary number and returns a string representing its octal (base-8) equivalent. Do not include leading zeros in the output (except for input '0').
Hint: Group the binary digits into groups of 3 from right to left, then convert each group to its octal digit.
- •1 <= len(binary_str) <= 20
- •binary_str contains only '0' and '1'
Examples
binary_to_octal('1010')'12'
Group from right: 001 010. 001 = 1, 010 = 2. So octal is 12. (Binary 1010 = Decimal 10 = Octal 12.)
binary_to_octal('111111')'77'
Group: 111 111. 111 = 7, 111 = 7. Octal is 77. (Binary 111111 = Decimal 63 = Octal 77.)
binary_to_octal('11001010')'312'
Group from right: 011 001 010. 011=3, 001=1, 010=2. Octal is 312. (Binary 11001010 = Decimal 202 = Octal 312.)
Need a Hint?
Edge Cases to Watch
- Empty input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Generators
Learn how to use Python generators and yield statements to process huge datasets with minimal memory footprints. Master generator expressions.
How to Convert String to Int in Python
Learn how to convert a string to an integer in Python using the int() function. Handle errors safely and convert numbers from binary, octal, or hex.
Python Type Conversions
Learn implicit and explicit type conversions in Python. Convert between strings, integers, floats, lists, sets, and dictionaries.
Python Decorators vs Decorator Design Pattern: The Key Differences
Compare Python decorators and the classic decorator design pattern. Understand the differences between definition-time function wrapping and runtime dynamic object composition with runnable code.