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

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