Python 基礎知識簡單

二進位到十進制轉換

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

問題陳述

簡單

寫一個函數 binary_to_decimal(binary_str) ,它接受一個表示二進制數(僅包含“0”和“1”)的字串,並傳回其十進制(以 10 為基數)整數等值。

二進制數中的每個數字代表 2 的冪,從最右邊的數字 (2^0) 開始。例如,二進位“1010”= 1×23 + 0×22 + 1×21 + 0×2⁰ = 8 + 0 + 2 + 0 = 10。

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

範例

Example 1
Input
binary_to_decimal('1010')
Output
10
Explanation

1×2³ + 0×2² + 1×2¹ + 0×2⁰ = 8 + 0 + 2 + 0 = 10.

Example 2
Input
binary_to_decimal('1111')
Output
15
Explanation

1×2³ + 1×2² + 1×2¹ + 1×2⁰ = 8 + 4 + 2 + 1 = 15.

Example 3
Input
binary_to_decimal('10000')
Output
16
Explanation

1×2⁴ = 16.

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

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