Python 基礎知識簡單

八進位到二進位轉換

“八進位到二進位轉換”問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 octal_to_binary(octal_str) ,它接受一個表示八進制數(以 8 為基數,數字 0-7)的字串,並傳回一個表示其等效二進位(以 2 為基數)的字串。不要在輸出中包含前導零(輸入“0”除外)。

提示:將每個八進制數字轉換為其 3 位二進制數字並連接。

約束條件
  • 1 <= len(octal_str) <= 10
  • octal_str contains only digits '0' through '7'

範例

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

1 = 001, 2 = 010. Concatenate: 001010. Remove leading zeros: 1010.

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

7 = 111, 7 = 111. Concatenate: 111111.

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

3 = 011, 1 = 001, 2 = 010. Concatenate: 011001010. Remove leading zero: 11001010.

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

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