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.