Python 基础知识简单

将数字/数字转换为单词

“将数字/数字转换为单词”问题的详细指南和 Python 实现。

问题陈述

简单

编写一个函数 number_to_words(n) ,它接受一个非负整数 n 并返回一个字符串,其中每个数字都转换为其英文单词,并以空格分隔。

数字-单词映射:0=“零”、1=“一”、2=“二”、3=“三”、4=“四”、5=“五”、6=“六”、7=“七”、8=“八”、9=“九”。

例如,123→“一二三”。

约束条件
  • 0 <= n <= 10^9

示例

Example 1
Input
number_to_words(123)
Output
'One Two Three'
Explanation

1 → 'One', 2 → 'Two', 3 → 'Three'. Joined with spaces.

Example 2
Input
number_to_words(405)
Output
'Four Zero Five'
Explanation

4 → 'Four', 0 → 'Zero', 5 → 'Five'.

Example 3
Input
number_to_words(0)
Output
'Zero'
Explanation

Single digit 0 → 'Zero'.

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

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