Python 编程中整数到英文单词的转换

pythonserver side programmingprogramming更新于 2026/1/24 16:44:17

假设我们有一个数字。该数字可以是 0 到 231 – 1 之间的任何数字。我们必须将数字转换为单词。因此,如果数字为 512,则结果将为五百一十二。

要解决这个问题,我们将遵循以下步骤 −

  • 定义一些列表,如 less_than_20,它将保存从一到十九的所有单词

  • 另一个数组,如十位,用于保存十位、二十位、三十位等,直到九十位

  • 另一个千位数组,用于保存千位、百万位和十亿位

  • 定义一个名为 helper() 的函数,它将接受 n

  • 如果 n 为 0,则返回空白字符串

  • 否则,当 n < 20 时,则返回 less_than_20[n] + 空格

  • 否则,当 n < 100,则返回 tens[n/10] + 空格 + helper(n mod 10)

  • 否则返回 less_than_20[n/100] + “Hundred” + helper(n mod 100)

  • 从 main 方法中,执行以下操作

  • 如果 num 为 0,则返回 “Zero”

  • ans := 空字符串,i := 0

  • while num > 0

    • 如果 num mod 1000 不为 0,则

      • ans := helper(num mod 1000) + thousands[i] + blank space + ans


  • 返回 ans

让我们看看下面的实现以便更好地理解 −

示例

class Solution(object):
less_than_20 = ["", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen"]
   tens = ["","Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
   def numberToWords(self, num):
      if num == 0:
         return "Zero"
      ans = ""
      i = 0
      while num > 0:
         if num % 1000 != 0:
            ans = self.helper(num % 1000) + Solution.thousands[i] + " " + ans
            i += 1
            num //= 1000
         return ans.strip()
   def helper(self, n):
      if n == 0:
         return ""
      elif n < 20:
         return Solution.less_than_20[n] + " "
      elif n < 100:
         return Solution.tens[n//10] + " " + self.helper(n % 10)
      else:
         return Solution.less_than_20[n // 100] + " Hundred " +
self.helper(n % 100)
ob = Solution()
print(ob.numberToWords(512))
print(ob.numberToWords(7835271))

输入

512
7835271

输出

Five Hundred Twelve
Seven Million Eight Hundred Thirty Five Thousand Two Hundred Seventy One

相关文章


有用资源