Python 基礎知識簡單

十六進位到十進制轉換

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

問題陳述

簡單

寫一個函數 hex_to_decimal(hex_str) ,它接受一個表示十六進制數字(以 16 為基數,數字 0-9 和 A-F,不區分大小寫)的字串,並傳回其等值的十進制(以 10 為基數)整數。

在十六進位中,A=10、B=11、C=12、D=13、E=14、F=15。每個數字代表16的冪。

約束條件
  • 1 <= len(hex_str) <= 8
  • hex_str contains only valid hex characters (0-9, a-f, A-F)

範例

Example 1
Input
hex_to_decimal('1A')
Output
26
Explanation

1×16¹ + A(10)×16⁰ = 16 + 10 = 26.

Example 2
Input
hex_to_decimal('FF')
Output
255
Explanation

F(15)×16¹ + F(15)×16⁰ = 240 + 15 = 255.

Example 3
Input
hex_to_decimal('2B')
Output
43
Explanation

2×16¹ + B(11)×16⁰ = 32 + 11 = 43.

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

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