Back to Practice Dashboard
Python BasicsEasy

Binary to Octal conversion

Learn how to solve the 'Binary to Octal conversion' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

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.

Constraints
  • 1 <= len(binary_str) <= 20
  • binary_str contains only '0' and '1'

Examples

Example 1
Input
binary_to_octal('1010')
Output
'12'
Explanation

Group from right: 001 010. 001 = 1, 010 = 2. So octal is 12. (Binary 1010 = Decimal 10 = Octal 12.)

Example 2
Input
binary_to_octal('111111')
Output
'77'
Explanation

Group: 111 111. 111 = 7, 111 = 7. Octal is 77. (Binary 111111 = Decimal 63 = Octal 77.)

Example 3
Input
binary_to_octal('11001010')
Output
'312'
Explanation

Group from right: 011 001 010. 011=3, 001=1, 010=2. Octal is 312. (Binary 11001010 = Decimal 202 = Octal 312.)

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor