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


假设我们有一个数字。这个数字可以是介于 0 到 231-1 之间的任何数字。我们要将这个数字转换成英文单词。所以如果这个数字是 512,那么结果将是 Five hundred twelve(五百一十二)。

为了解决这个问题,我们将按照以下步骤进行

  • 定义一些列表,例如 less_than_20,它将包含一到十九的所有单词

  • 另一个 tens 数组,它将包含二十、三十,直至九十

  • 另一个 thousands 数组,它将包含一千、百万和十亿

  • 定义一个名为 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

  • 当 num > 0 时

    • 如果 num mod 1000 不为 0,则

      • ans := helper(num mod 1000) + thousands[i] + 一个空格 + 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

更新于:09-Jun-2020

2K+浏览

职业启动

通过完成课程获得认证

开始吧
广告
© . All rights reserved.