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

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