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

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