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 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。