Python 基础知识简单

二进制到八进制转换

“二进制到八进制转换”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 binary_to_octal(binary_str) ,它接受一个表示二进制数的字符串,并返回一个表示其八进制(以 8 为基数)等价物的字符串。不要在输出中包含前导零(输入“0”除外)。

提示:将二进制数字从右到左分成 3 组,然后将每组转换为八进制数字。

约束条件
  • 1 <= len(binary_str) <= 20
  • binary_str contains only '0' and '1'

示例

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?
考虑使用特定于数字的数据结构,例如集合或堆。
Edge Cases to Watch
  • 空输入结构
  • 单元素输入
  • 大数值范围

准备好解决了吗?

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

在编辑器中打开
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推荐的 Python 资源

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。